Results 1 to 2 of 2
  1. #1
    ClariceT is offline Novice
    Windows 10 Access 2016
    Join Date
    Apr 2022
    Posts
    9

    SQL Sum with optional fields

    Hi!

    I'm new here and I have a problem: in a query I need to add fields that are in a linked xls. I used the code below and it worked:

    Code:
    SELECT [tblReferences].Cod, [tblReferences].Name, Nz([Ref_1])+Nz([Ref_2])+Nz([Ref_3])+Nz([Ref_4])+Nz([Ref_5])+Nz([Ref_6]) AS Ref_Total
    FROM [tblReferences]
    ORDER BY [tblReferences].Name;
    The problem is that the fields 'Ref_5' and 'Ref_6' will not always be present in the linked file, and when this happens it gives an error.

    What I need: That the inclusion of these fields in the sum is conditioned to their presence in the linked table, therefore being ignored if they are not in the file.



    Can someone help me?

  2. #2
    CJ_London is offline VIP
    Windows 10 Access 2010 32bit
    Join Date
    Mar 2015
    Posts
    11,411
    you'll need to use some vba code to check for the existence of the field(s) and then dynamically build your query

    perhaps something like

    Code:
    dim fld as DAO.field
    dim sqlstr as string
    
    
    sqlStr="SELECT [tblReferences].Cod, [tblReferences].Name"
    for each fld in currentdb.tabledefs("name of your linked table").fields
        if fld.name like "ref_" then sqlstr = sqlstr & ", nz(" & fld.name & ")"
    next fld
    
    sqlstr=sqlstr & " AS Ref_Total FROM [tblReferences] ORDER BY [tblReferences].Name;"
    debug.print sqlstr 'to check it has been correctly created
    
    currentdb.querydefs("name of your query").sql=sqlstr
    
    'or if you have a form
    forms!myform.recordsource=sqlstr
    
    


    this is aircode so their may be typos but should get you on your way




Please reply to this thread with any new information or opinions.

Similar Threads

  1. Argument Not Optional
    By Eranka in forum Access
    Replies: 2
    Last Post: 10-22-2018, 12:58 PM
  2. Argument not optional.
    By Homegrownandy in forum Programming
    Replies: 4
    Last Post: 05-11-2017, 03:23 AM
  3. error argument not optional
    By slimjen in forum Programming
    Replies: 10
    Last Post: 03-20-2013, 09:31 PM
  4. Replies: 2
    Last Post: 10-23-2012, 12:18 PM
  5. multiple optional criteria
    By TheShabz in forum Programming
    Replies: 7
    Last Post: 07-05-2011, 05:13 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums