I have a SQL VBA query for updating values in several textboxes on a form on the click of a button.
The query takes the input from the multiple label name captions on the form. So caption of Label1 will be input for TextBox1, Label2 caption for Textbox2 etc.
I am trying to pass the label name through a variable to the query. However the following error is returned on the line where value of variable b is generated:
"Microsoft Access can't find the field '&labelname&'referred to in your expression.
My code is below. I want to use a variable so that later I can make it a function to accept the label name and return the recordset value. In this way I will be able to avoid approx. 150 lines of code as I have to update 20 to 25 textboxes with the input from same number of labels.
Private Sub Command111_Click()
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim ssql As String
Dim labelname As String
Dim b As String
Set dbs = CurrentDb
'--------------------------------------------------------------------------- ----
labelname = "Label24"
b = [Forms]![Bal_Sheet]![& labelname &].Caption
ssql = "select sum(a.[Bal Fwd]) from Trial_Balance a,Act_Master b where a.GBOBJ = b.object and a.GBSUB = b.sub and b.Cat = " & "'" & b & "'"
Debug.Print ssql
Set rs = dbs.OpenRecordset(ssql, dbOpenDynaset)
[Forms]![Bal_Sheet]![Text1].Value = rs(0)
'-------------------------------------------------------------------------------
rs.Close
Set rs = Nothing
dbs.Close
End Sub
Your expression:
b = [Forms]![Bal_Sheet]![& labelname &].Caption
Is not concatenating a string, as [Forms] and [Bal_Sheet] refer to objects.
Instead, you should use:
b = Forms("Bal_Sheet").Controls(labelname).Caption
Related
I'm having an issue with a piece of VBA I've written for Access. I have a table with a concatenation field 'Concat' (string field) and field called 'Age' (integer field with numerical values).
There are another 61 fields (named '0','1','2'...'60' respectively) where the code needs to work though: I want the code to loop through and, per record entry - for the VBA to Dlookup using the Concat + age fields to another table (called: tbl_Final_Probabilities) and pull back a probability and populate each of these 61 fields with the correct probability. These fields are set up at a numerical field, data type as Single.
The code pulls the correct probability but when I try to update the record for that field at the code line: "rs.Fields(a) = b" (also highlighted in code), I get the error message: "Run time error '3164': 'Field cannot be updated'".
All help welcome on how I need to correct this please, the code used is below.
Punch and pie.
Code:
Dim rs As DAO.Recordset
Dim a As Integer
Dim b As Single
Dim lookup As String
Set rs = CurrentDb.OpenRecordset("SELECT * FROM tbl_Circuit_plus_prob")
For a = 0 To 60
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
rs.Edit
lookup = rs!Concat & (rs!age + a)
b = DLookup("Prob_Date", "tbl_Final_Probabilities", "Concat2 = '" & lookup & "'")
rs.Fields(a) = b '- CODE BREAKS DOWN HERE
rs.Update
rs.MoveNext
Loop
End If
Next a
rs.Close
Set rs = Nothing
Thanks in advance for any and all help.
You loop is turned inside out:
Dim rs As DAO.Recordset
Dim a As Integer
Dim b As Single
Dim lookup As String
Set rs = CurrentDb.OpenRecordset("SELECT * FROM tbl_Circuit_plus_prob")
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
rs.Edit
For a = 0 To 60
lookup = rs!Concat & (rs!age + a)
b = DLookup("Prob_Date", "tbl_Final_Probabilities", "Concat2 = '" & lookup & "'")
rs.Fields(a).Value = b
Next
rs.Update
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
Your code: rs.Fields(a) = b addresses the field with the index 'a' (which is 0 in the first loop), in your table, this is probably an auto increment field and therefore cannot be updated. If you want to write in the fields with the names '0','1',... use this syntax: rs.Fields(x + a) = b, where x is the number of fields+1 (because your loop starts with 0) in the table existing before your field '0'.
I am having some trouble passing a decimal number from an access field (using a DAO recordset) to a vba variable. I have tried changing datatypes in access and vba (single / currency), but the same line keeps being highlighted in the debugger, with a Runtime error 94 "Invalid use of null".
The thing that is confusing me is, when I hold the cursor over the variable in the debugger; the quickinfo shows that the variable is holding the correct value, but the recordset field is null. This only happens for the Decimal field, Other fields (string / integer) are not highlighted.
The line that is higlighted in the debugger is rs!Field4 in the 'Start Loop block. The strange thing is that rs.Field3 sets the numField3 variable fine. The only difference between the two is that field 3 contains integers and field 4 contains decimals. Both were msAccess numbers, but i have changed to currency during problem solve.
Any feedback would be good
Thanks
Private Sub Command1_Click()
'Set Database and Recordset variables
Dim thisDB As DAO.Database
Dim rs As DAO.Recordset
Set thisDB = CurrentDb
Set rs = thisDB.OpenRecordset("tblTable1")
'Declare and set recordset variables variables
Dim strField1 As String
Dim strField2 As String
Dim numField3 As Currency
Dim numField4 As Currency
Dim dtField5 As Date
Dim dtField6 As Date
'Declare dynamic variables
Dim dtVar1 As Date
Dim intVar2 As Integer
Dim dtVar3 As Date
'DecalreSQL Variables
Dim num1 As Currency
Dim num2 As Currency
Dim num3 As Currency
Dim StrSQL As String
Dim strValues As String
'Start Loop
Do While Not rs.EOF
strField1 = rs!Field1
strField2 = rs!Field2
numField3 = rs!Field3
numField4 = rs!Field4
dtField5 = rs!Field5
dtField6 = rs!Field6
If strField1 = "This" And strField2 = "That" Then
'Perform calculations
dtVar1 = 0
dtVar3 = 0
num3 = 0
Do While dtVar3 < dtField6
If ’Something’ Then
This calculation sets variables
ElseIf ‘SomethingElse’ Then
This calculation sets variables
Else
This calculation sets variables
End If
'Build SQL Query and apprend to table
strValues = dtVar1& "," & num1 & "," &num2 & "," & num3
StrSQL = "INSERT INTO tblTable2 (Field1, Field2, Field3, Field4 );"
StrSQL = StrSQL & "VALUES ('" & strValues & "')"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
dtVar3 = dtVar1
Loop
End If
rs.MoveNext
Loop
rs.Close
End Sub
When you hold the cursor over the variable it hasn't been assigned yet. You're actually showing the last record's value that was assigned to the numField4 variable.
What that means is your current recordset field Field4 is actually a null. To assign it to the numeric variable you need to trap for that condition.
numField4 = Nz(rs!Field4, 0)
And you should probably repeat for Field3 to cover thst possibility too
I have a sub in VBA where I am fetching data from database on button click event
like below
Public Sub getNearestPfk(runNR As Integer)
Dim DB As dao.Database
Dim rs As dao.Recordset
Dim sqlString As String
Dim record As Object
Dim objPFK As Pfk
Dim i As Integer
i = 0
Set DB = CurrentDb
sqlString = " SELECT TOP 5 T_TEMP_DESTANCE_CAL.* FROM T_TEMP_DESTANCE_CAL WHERE RUNID = " & runNR & " ORDER by DISTANCE "
MsgBox (sqlStringGetNearestPFK)
Set rs = DB.OpenRecordset(sqlString)
Do Until rs.EOF
objPFK.ID = rs!ID
objPFK.fistName = rs!firstName
objPFK.lastName = rs!lastName
objPFK.distance = rs!distance
objPFK.duration = rs!duration
objPFK.address = rs!address
arrayObjPFK(i) = objPFK
rs.MoveNext
i = i + 1
Loop
rs.Close
Set rs = Nothing
Set DB = Nothing
End Sub
Now I have all the data Which I want to display
how should I display this data in listbox so on this button click a listbox will populate
You can set the list box property called Row Source Type to Table/Query and then your Row Source property to the SQL statement.
If you want to update the list box, simply update the Row Source.
this code is to populate textboxes in form where sql query is fatching data from table RR_info on the behalf of hr_id. it compare hr_id of rr_info with the bounded value of listbox.
Private Sub Form_Load()
Dim SQL As String
Dim db As Database
Dim rs As DAO.Recordset
SQL = "select * from RR_info where hr_id = " & Forms![hhrrr]![List38] & ";"
Set db = CurrentDb
Set rs = db.OpenRecordset(SQL)
'DoCmd.RunSQL SQL 'at this point it gives me error 2342
Me.RR_ID.value = rs!RR_ID
Me.HR_ID.value = rs!HR_ID
Me.Room_No.value = rs![Room No]
Me.No_of_Beds.value = rs!No_of_Beds
Me.Room_Category.value = rs!Room_Category
Set rs = Nothing
Set db = Nothing
End Sub
You dont need string "DoCmd.RunSQL SQL".
And it is better to use .Value insted of .Text
Using VBA, how can I search for a text string, for example "CHIR", in a table called "ServiceYES", in the field "Service".
After that, I would like to save the neighboring field for all the rows that "CHIR" exists in the table "ServicesYES". The "ServiceYES" table is below:
I basically, want to find all the "CHIR" in "Service" column and then save the names which are on the left of the CHIR, eg "FRANKL_L", "SANTIA_D" as an array.
Thanks for all your help in advance.
Start by creating a SELECT query.
SELECT Code_Perso
FROM ServicesYES
WHERE Service = 'CHIR';
Use SELECT DISTINCT Code_Perso if you want only the unique values.
Add ORDER BY Code_Perso if you care to have them sorted alphabetically.
Once you have a satisfactory query, open a DAO recordset based on that query, and loop through the Code_Perso values it returns.
You don't need to load them directly into your final array. It might be easier to add them to a comma-separated string. Afterward you can use the Split() function (assuming you have Access version >= 2000) to create your array.
Here's sample code to get you started. It's mostly standard boiler-plate, but it might actually work ... once you give it "yourquery".
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strItems As String
Dim varItems As Variant
Set db = CurrentDb
Set rs = db.OpenRecordset("yourquery", dbOpenSnapshot)
With rs
Do While Not .EOF
strItems = strItems & "," & !Code_Perso
.MoveNext
Loop
.Close
End With
If Len(strItems) > 0 Then
' discard leading comma '
strItems = Mid(strItems, 2)
varItems = Split(strItems, ",")
Else
MsgBox "Oops. No matching rows found."
End If
Set rs = Nothing
Set db = Nothing
I tested this and it seems to work. This function will pull all records where ServiceYes='CHIR' and dump the Code_Person value into an array which it will return:
Function x() As String()
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset( _
"Select * from ServiceYES where Service='CHIR'")
Dim Arr() As String
Dim i As Integer
While rst.EOF = False
ReDim Preserve Arr(i)
Arr(i) = rst.Fields("Code_Person")
i = i + 1
rst.MoveNext
Wend
x = Arr
End Function
Sample Usage:
Debug.Print x()(0)
Paolo,
Here is something I threw together in a few minutes. You can add it to the VBA editor in a module. It uses a trick to get the RecordCount property to behave properly. As for returing the array, you can update the function and create a calling routine. If you need that bit of code, just post a comment.
Thanks!
Option Compare Database
Function QueryServiceYES()
Dim db As Database
Dim saveItems() As String
Set db = CurrentDb
Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("SELECT Code_Perso, Service, Favorites " & _
"FROM ServiceYES " & _
"WHERE Service = 'CHIR'")
'bug in recordset, MoveFirst, then MoveLast forces correct invalid "RecordCount"
rs.MoveLast
rs.MoveFirst
ReDim Preserve saveItems(rs.RecordCount) As String
For i = 0 To rs.RecordCount - 1
saveItems(i) = rs.Fields("Code_Perso")
rs.MoveNext
Next i
'print them out
For i = 0 To UBound(saveItems) - 1
Debug.Print saveItems(i)
Next i
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
End Function