How to reference control names dynamically in MS Access - ms-access

I have the following code in an MS Access Form object.
Private Sub UpdatePMText(sLang As String)
'Used to pass both Mandate and Language Info to called Sub that will execute the queries
Dim iMandate As Integer
'Check if there is text in the box.
If Me.Controls("txtInput_PM_" & sLang & "_DRAFT") = Null Or Me.Controls("txtInput_PM_" & sLang & "_DRAFT") = "" Then
MsgBox ("There is no text in the " & sLang & " DRAFT Field." & vbNewLine & "The operation will not be executed.")
Exit Sub
End If
iMandate = Me.txtMandateID
Call modUpdateText.macro_PMText(iMandate, sLang)
End Sub
If I refer to the Controls directly and simply type out the names of the forms, for example txtInput_PM_EN_DRAFT then the code works as intended.
The error message I get is that Access can't find the "Field" I'm referring to when I am on the first IF statement line. I have tried changing the .Controls to .Fields but that didn't work either.
I do not want to repeat the same code for every language I need to run. How do I reference control names dynamically in MS Access? What am I missing?

I think you need to add some basic troubleshooting. The answer is probably simpler than you think. It's likely you're just trying to lookup a textbox with mispelled name or it's failing on the Null comparison (as suggested by #HansUp)
I would try modifying your basic sub and testing it with this subroutine. As long as your code is in your current form and you're not referencing a subform your method will work.
Private Sub UpdatePMText(sLang As String)
Const ERR_MISSING_CONTROL As Long = 2465
On Error GoTo Err_UpdatePMText
Dim sTextBox As String
sTextBox = "txtInput_PM_" & sLang & "_DRAFT"
'Check if there is text in the box.
If Nz(Me.Controls(sTextBox).Value, "") = "" Then
MsgBox ("There is no text in the " & sLang & " DRAFT Field." & vbNewLine & "The operation will not be executed.")
Exit Sub
End If
Exit Sub
Err_UpdatePMText:
If Err.Number = ERR_MISSING_CONTROL Then
MsgBox "Error: No Such Textbox: " & sTextBox
Else
MsgBox "Error Looking Up Textbox: """ & sTextBox & """" & vbCrLf & Err.Description
End If
End Sub

Related

How to make a command button collection ms access

Let’s say i have a 100 command buttons and images in an access form i need to deal with them as groups for example in English : Group1 includes commandbutton1 To Commandbutton10 and Image1 To Image10
me.group1.visible = false
The result would be hide buttons from 1 To 10 and hide images from 1 to 10
I need to declare the groups names and each group includes which command buttons and images then deal with them as i mentioned above how can i do that ? thanks in advance
One thing that you could look at is using the .Tag property of the controls. You could either just have a single piece of text and check for equality, or else you could have several pieces of text and check if a piece of text exists (which allows you to have controls being members of several groups). A basic example is:
Private Sub cmdVisible_Click()
On Error GoTo E_Handle
Dim ctl As Control
For Each ctl In Me.Controls
If ctl.Tag = "Group1" Then
ctl.Visible = Not ctl.Visible
End If
Next ctl
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "frmVisible!cmdVisible_Click", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
Regards,

Using multiple Combo-boxes in Access as query criteria dont work together but using one combo-box works ?? How to make all Combo-boxes work?

I looks like when i use one Combo-box as a criteria works just fine however using more than that though following the same steps doesn't work . I don't use SQL i do use the Design view though.
How to make all combo boxes works together to provide the needed criteria.
If you are looking to filter a form or list box using data selected from several combo boxes, then you will need to build up the RowSource "on the fly" based on the selections made.
Below is some sample code that uses selections from 2 combo boxes (cboCountry and cboRMZone) to create the RowSource for a list box (lstCountry):
Private Sub cboCountryZone_AfterUpdate()
Call sSearchMultiple
End Sub
Private Sub cboRMZone_AfterUpdate()
Call sSearchMultiple
End Sub
Private Sub Form_Load()
Call sSearchMultiple
End Sub
Private Sub sSearchMultiple()
On Error GoTo E_Handle
Dim strSQL As String
If Not IsNull(Me!cboCountryZone) Then strSQL = strSQL & " AND CountryZone_PK=" & Me!cboCountryZone
If Not IsNull(Me!cboRMZone) Then strSQL = strSQL & " AND RMZone_PK=" & Me!cboRMZone
If Left(strSQL, 4) = " AND" Then
strSQL = " WHERE " & Mid(strSQL, 6)
End If
If Len(strSQL) > 0 Then
Me!lstCountry.RowSource = "SELECT CountryName FROM dbo_svr_Country " & strSQL & " ORDER BY CountryName ASC;"
Else
Me!lstCountry.RowSource = "SELECT CountryName FROM dbo_svr_Country ORDER BY CountryName ASC;"
End If
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "Form3!sSearchMultiple", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
Regards,

MS Access VBA Reference

I have this database and it was working perfect, but today it started hating me. I started getting a Compile error: Can't find project or library. I looked around and found that when using the front end on a different computer, under VBA and references, it was missing a reference for Microsoft Word 15.0 Object Library.
My computer I have the Microsoft Word 16.0 Object Library checked. How can I get this to work on other computers with 15.0 and 16.0?
Here is the code
Private Sub cmd_LocateFile_Click()
On Error GoTo Error_Handler
Dim sFile As String
Dim sFolder As String
Dim ID As Long
Dim sTarget As String
sFile = FSBrowse("", msoFileDialogFilePicker, "All Files (*.*),*.*")
If sFile <> "" Then
sFolder = ("\\aiowima23fp1\Ecological Sciences and Engineering\Cultural Resources\New - Cultural Resources Request Database") & "\" & sAttachmentFolderName & "\"
If FolderExist(sFolder) = False Then MkDir (sFolder)
ID = RequestID_FK ' Set current record id.
sTarget = sFolder & CStr(ID) & "-" & GetFileName(sFile)
If CopyFile(sFile, sFolder & GetFileName(sTarget)) = True Then
Me!FullFileName.Value = sTarget
Else
End If
End If
Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: " & sModName & "\cmd_LocateFile_Click" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub
Adding references to Word during development has the advantage to be able to use strongly typed word objects and thus being able to take advantage of IntelliSense. But these references are, as you have experienced, sensible to versioning. Therefore, I suggest you remove the reference to Word once development is achieved. You will also have to replace all Word-related types by Object, i.e. use late binding. This makes the application more robust with respect to versioning.
You can get an existing Word instance which is already open or open a new one with this code snippet, without any references to Word DLLs.
Public Function GetWordApplication() As Object
'Gets an active Word application or opens a new Word instance.
'Raises Error No. 8 if word cannot be opened.
On Error Resume Next
'Find existing instance of Word
Set GetWordApplication = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Not found, create new instance.
Set GetWordApplication = CreateObject("Word.Application")
End If
'Following code is optional. You can instead test for Nothing at the call site
On Error Goto 0
If GetWordApplication Is Nothing Then
Err.Raise 8, "YourApp.GetWordApplication", "Word could not be opened."
End If
End Function

Parameter Value on Combo Box

I am trying to filter a subform with a combobox. What I have works, but it keeps bringing up an "Enter Parameter Value" textbox. When I enter the value I want to filter with, it searches the subform no problem. I would prefer to not have to enter the value though as it defeats the purpose of the combobox.
Here is my code for the ComboBox,
Private Sub ComboFE_AfterUpdate()
On Error GoTo Proc_Error
If IsNull(Me.ComboFE) Then
Me.SubFormPF.Form.Filter = ""
Me.SubFormPF.Form.FilterOn = False
Else
Me.SubFormPF.Form.Filter = "Lead_FE = " & Me.ComboFE
Me.SubFormPF.Form.FilterOn = True
End If
Proc_Exit:
Exit Sub
Proc_Error:
MsgBox "Error " & Err.Number & " in setting subform filter:" & vbCrLf & Err.Description
Resume Proc_Exit
End Sub
I have checked and made sure all the names are correct and match the corresponding items on my form.
Any Ideas?
Many Thanks
When applying a filter on a text column, the value needs quotes.
Me.SubFormPF.Form.Filter = "Lead_FE = '" & Me.ComboFE & "'"
To avoid problems if the value itself contains quotes, use Gustav's CSql() function from here: https://stackoverflow.com/a/36494189/3820271
Me.SubFormPF.Form.Filter = "Lead_FE = " & CSql(Me.ComboFE.Value)
This works for all data types.

my for next loop is not working and gives error94

Cannot understand why my for and next loop is not working. What I am trying to do is to print a report for the same number of records details depending on the number value of a particular field called [nts].
If the field is empty it tells me I have error: 94. If the field has a value it goes to errorhandler mention in the program. Can any body be so kind and help me please? Thank you in advance :)** I am using ACCESS2007
Option Compare Database
Option Explicit
Private Sub Report_Close()
' Delete previous data from tabMeal
DoCmd.SetWarnings False
DoCmd.RunSQL "Delete from tabAmeal"
End Sub
Private Sub Report_Load()
Dim intNOM As Integer
'NOM means number of nights meals
Dim mTimes As Integer
On Error GoTo errorhandler
intNOM = 1
mTimes = 0
mTimes = DLookup("nz([nts],0)", "tabAmeal", "[nts] > 0")
'mTimes means number of meals
If mTimes = 0 Then
MsgBox "File is empty GO to Query" & vbCrLf & "Error - Run the Query", vbQuestion
Else
'now print the information found in table "tabmeal" number of times depending on the value field "nts"
For intNOM = 1 To mTimes
DoCmd.OpenReport "repAmeal?", acViewPreview
Next intNOM
End If
errorhandler:
MsgBox "Error #:- " & Err.Number & vbCrLf & "LOOP not working" & vbCrLf & "Must find why this error" & vbCrLf & Err.Description
End Sub
Private Sub Report_NoData(Cancel As Integer)
MsgBox "Please note that you have no records to report." & vbCrLf & "You have to run the QUERY to get the required informatio."
End Sub
The first problem:
Nz() must be used outside of DLookup, not inside:
mTimes = Nz(DLookup("[nts]", "tabAmeal", "[nts] > 0"), 0)
The second problem, I'm not sure. You can't open a report multiple times in acViewPreview (it will open only once), but it shouldn't give an error.
What is the exact error message you get when nts > 0 ?
Oops. You need Exit Sub befor your errorhandler: line - the code simply enters the error handler, without there being an error. :)