VBA - Change the field name alias in a query
Posted on 2008-10-22
How do you change the alias name in a query object via VBA? You might ask why; I have one form that I want to display the results from multiple query. Each query has different fields name and I want the one form to be generic enough to handle all the option. So, I have a generic form with 30 fields. Each labaled text1, text2, text3, text4....
The user selects the report type on the main form. In VBA, the process does the following...
1. looks at the report type to determine which table to use...
2. Filters out the the records need from the results by creating a strSQL
3. Assigns the strSQL to the form.recordsource.
Dim ReportType As String
ReportType = Me.cmb_reporttype
If ReportType = "Positions" Then
strSQL = "select * from WSOReportingAllpositions"
Me!WSOReportingMainResults.Form.RecordSource = strSQL
Since each query has different field values; I want to parse through each and set the alias name automatically... like this...
Counter = 1
Set qdf = db.QueryDefs(QueryName)
For Each fld In qdf.Fields
FieldValue = fld.Name
SourceField = fld.SourceField
Source = fld.SourceTable
If fld.Name Like "text*" Then
fld.Name = "text" & Counter & ":" & SourceField
Counter = Counter + 1
I am having trouble with this statement: fld.Name = "text" & Counter & ":" & SourceField. It will not allow me to change the field name in the query. For example:
Column 1 has "Asset_Name". I want text1: Asset_Name OR another way "SELECT Asset_Name AS text1, ...
How can I accomplish this? Thanks for the assistance.