MSAccess sum if based on columnname


I have a table with many columns. Some columnnames end with an underscore "_".
I would like to make a sum in a new column where only the values of the columns ending with the underscore are taking into account.
Is there a function available that can do this, or can someone build me one?

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dale FyeOwner, Developing Solutions LLCCommented:
If you know what those column names are at design time, then you could create a computed column in a query, something like:

Select field1, field2, NZ([Field3_],0) + NZ([Field4_], 0) + NZ([Field5_], 0) as Computed
From yourTable

If you don't know the column names that will end in the underscore, you could open a recordset based on the table,  loop through the fields collection of that recordset checking for field names that include the underscore, and build a SQL string

Dim rs as DAO.Recordset
Dim strSQL as string, intLoop as integer
Set rs = currentdb.openrecordset("SELECT * FROM yourTable WHERE 1 = 2")
For intLoop = 0 to rs.fields.count - 1
    if right(rs.fields(intLoop).name, 1) = "_" Then
        strSQL = strSQL & " + " & "NZ([" & rs.fields(intLoop).name & "],0)"
    End if
strSQL = "SELECT Field1, Field2, " & Mid(strSQL, 4) & " FROM yourTable"

Davy2270Author Commented:
The second solution is what I need.
However I am not sure what I need to do now.
Actually I would like to have the computed field in a query next to other queried fields.
Could you show me the (detailed) steps I need to take to get there.
Dale FyeOwner, Developing Solutions LLCCommented:

I'm not sure why you would not know the names of those columns at design time, unless you are importing data from a file whose format can change over time.

I think what I provided is pretty detailed.

1.  Obviously, you will need to put that code in a click event of a command button, or something like that.
2.  Replace "yourTable" with the name of the table you are using.
3.  Replace "Field1" and "Field2" with the field names you want to include in the query.

4.  What you do next depends on the purpose of this SQL string.  You could save it as the SQL property of an already saved query, or you could use it as the recordsource for a form or report.
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

Davy2270Author Commented:
Indeed the columnnames do change over time.
Your code seems to work fine.
But I do not know how I can get it to work in a query.
How do I save it as an SQL property of a query?
Dale FyeOwner, Developing Solutions LLCCommented:
If you have a saved query (qry_SomeName), you can set the SQL property of that query with:

Currentdb.QueryDefs("qry_SomeName").SQL = strSQL

you could then use that query as the Recordsource for a form or report, our use the OpenQuery method to actually open the SELECT query.

Davy2270Author Commented:
I pasted that line in the module.
CurrentDb.QueryDefs("qry 001").SQL = strSQL
 I get an error at that line saying:
Item not found in this collection.
Davy2270Author Commented:
Query name was misspelled.
However, now I get this error message:
Invalid SQL statement; expected 'DELETE','INSERT','PROCEDURE','SELECT' or 'UPDATE'.
Dale FyeOwner, Developing Solutions LLCCommented:
Then are you sure that "qry 001" exists?  If it does, then that syntax should work.

If you want to create a new query, you can use the CreateQuerydef method (from Access Help):

Sub CreateQueryDefX()

   Dim dbsNorthwind As Database
   Dim qdfTemp As QueryDef
   Dim qdfNew As QueryDef

   Set dbsNorthwind = OpenDatabase("Northwind.mdb")

   With dbsNorthwind
      ' Create temporary QueryDef.
      Set qdfTemp = .CreateQueryDef("", "SELECT * FROM Employees")
      ' Open Recordset and print report.
      GetrstTemp qdfTemp

      ' Create permanent QueryDef.
      Set qdfNew = .CreateQueryDef("NewQueryDef", "SELECT * FROM Categories")
      ' Open Recordset and print report.
      GetrstTemp qdfNew
      ' Delete new QueryDef because this is a demonstration.
      .QueryDefs.Delete qdfNew.Name
   End With

End Sub

Dale FyeOwner, Developing Solutions LLCCommented:
Post all of the code for this process.  My guess is that you forgot the line that looks like:

strSQL = "SELECT Field1, Field2, " & Mid(strSQL, 4) & " FROM yourTable"

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Davy2270Author Commented:
Thanks fyed.
This works perfect.
Thanks for your guidance and patience.

Dale FyeOwner, Developing Solutions LLCCommented:
Glad to help
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.