Forms(frmName) NOT WORKING - windows

I am trying to use a string variable instead of hardcoding the forms name as below.
FrmMainControl.Controls
but want to use this.
Forms("FrmMainControl").Controls
However, i get the error Sub or Function not defined. Please help. This is in VBA btw.

Assuming the form is loaded you can search the UserForms collection;
Dim form As UserForm: Set form = getInstanceOfLoadedUfrm("frmMainControl")
If Not form Is Nothing Then
MsgBox form.Controls.Count
Else
'//load
Set form = UserForms.Add("frmMainControl")
MsgBox form.Controls.Count
End If
Function getInstanceOfLoadedUfrm(name As String) As UserForm
name = UCase$(name)
For Each form In UserForms
If (Ucase$(form.name) = name) Then
Set getInstanceOfLoadedUfrm = form
End If
Next
End Function

Related

Why does my global Dictionary variable not properly set in VBScript?

I am using ASP Classic with VBScript, and I have been trying to create a Dictionary, populate it, then have it accessible globally. The way my page is set up, I have a main Class for one of my Objects, that has multiple Display subs, and changing a "displaymode" hidden input causes the page to submit and reload a new page depending on which displaymode matches which display sub. It has worked well for everything so far, but I cannot figure out how to assign a Dictionary globally.
I have the Dictionary variable declared and set globally, then in one sub I call another sub to assign it. I can then use the Dictionary perfectly fine inside both subs, but when I try to use it in anything else outside those subs, it is empty. Here is an example:
Dim dict
Set dict = CreateObject("Scripting.Dictionary")
DisplayObj
Sub DisplayObj()
Dim example
Set example = New exampleClass
With example
.Display
End With
End Sub
Class exampleClass
Public Sub Display()
Select Case Request("Display Mode")
Case "displayFull"
DisplayFull
Case "displaySingle"
DisplaySingle
End Select
End Sub
Public Sub DisplayFull()
SetList()
response.write ""& dict(0) &""
End Sub
Public Sub SetList()
dict.Add 0, "hello"
End Sub
Public Sub DisplaySingle()
response.write ""& dict(0) &""
End Sub
End Class
So when the page is set to displayFull and the DisplayFull sub is called, the dict variable is set properly and displays "hello". I have a click event change the display mode to DisplaySingle, and when that loads it displays nothing, and says the dict variable is empty. How can I have the SetList sub set the Dictionary globally?

Expected Function or variable vb6.0

Hello i am coding in Visual Basic 6.0 and i have this error, i am trying to make a button inserting data in database.
Expected Function or variable
This is my code
Private Sub Command1_Click()
With ConString.Recordset.AddNew
!ID = txtID
!Emri = txtEmri
!Mbiemri = txtMbiemri
!Datelindja = txtData
!Telefon = !txtTelefon
!Gjinia = gender
!Punesuar = job
!Martese = cmbMartese
!Vendlindja = txtVendlindje
End With
End Sub
txtID is textbox
txtEmri is textbox
txtMbiemri is textbox
txtData is date picker
txtTelefon is textbox
gender is a string that takes value if a radio button is clicked
job is an integer if a checkbox is clicked
cmbMartese is combo box
txtVendlindje is textbox
Thank you in advance.
#JohnEason gave you the right answer. But there's another error in the line !Telefon = !txtTelefon, if I'm not mistaken. It should read !Telefon = txtTelefon, i.e. without the exclamation mark in front of txtTelefon.
I'm also not a big fan of that coding style. I prefer to not rely on default properties, but instead "spell out" the whole term, e.g.
With ConString.Recordset
.AddNew
!ID = txtID.Text
!Emri = txtEmri.Text
!Mbiemri = txtMbiemri.Text
!Datelindja = txtData.Text
!Telefon = txtTelefon.Text
' Since VB6 doesn't provide Intellisense for variables, I prefer to use some
' kind of hungarian notation for variable names, in this case sGender or strGender for a string variable
!Gjinia = gender
' Same here: iJob or intJob for an integer variable
!Punesuar = job
' You need to specify that you want the selected item of a combobox
!Martese = cmbMartese.List(cmbMartese.ListIndex)
!Vendlindja = txtVendlindje.Text
' If you're done setting column values and don't do so somewhere else,
' you also need to add a .Update statement here in order to finish the
' .AddNew action and actually persist the data to the database.
' .Update
End With
End Sub
As pointed out below by #JohnEason, there's also potentially an .Update statement missing within the With/End With block

Is there a built in MS Access VBA Event to simplify Data Verification and SetFocus

Bit of a rookie issue here. How do you deal with data verification using Access Events? The problem is that when I use SetFocus to return the Cursor to the field with the errant data, Access goes through the _Exit and/or _LostFocus Events of the next Control in the Tab Order. If those include data validation procedures, the desired SetFocus is circumvented.
Using techturtles answer, I came up with this "solution" (read "hack").
Private Sub ServicingEmployee_LostFocus() 'Check data validity
If dataEntryCancelled Then Exit Sub
Dim cntrl As Control
Set cntrl = Me.ServicingEmployee
Dim myResponse As Integer
If IsNull(cntrl.Value) Then
myResponse = MsgBox("This field cannot be left blank.", vbOKOnly, "Enter Date Collected")
dataErrorInPreviousField = True
**'Next line sets a Public Control**
Set controlWithDataEntryError = Me.ServicingEmployee
End If
End Sub
Private Sub Client_GotFocus() '**Check for data Error in previous Control according to Tab Order**
If dataErrorInPreviousField Then Call dataErrorProc
End Sub
Public Sub dataErrorProc()
With controlWithDataEntryError
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End With
dataErrorInPreviousField = False
End Sub
Private Sub Client_Exit(Cancel As Integer) '**Example of Bypassing _Exit Event**
If dataEntryCancelled Or dataErrorInPreviousField Then Exit Sub
.
...
End Sub
My question is this: Is there a simpler way to accomplish this?
First, I would strongly encourage you to add table constraints in addition to your form validation, if you haven't already done so. Assuming this form is tied to a table in Access, just make sure the ServicingEmployee field (in the table) is set to required. That way, you have another level of validation making sure the field has a value.
For form validation, you can use either the form's or control's BeforeUpdate event. If you use the form's event, you only have to run the check once.
I would also suggest having a separate function (within the form) to check validity. Something like this (here, I'm using a form tied to an Employees table, with a first name and last field which should both be non-null):
Private Function isFormValid() As Boolean
' we start off assuming form is valid
isFormValid = True
If IsNull(Me.txtFirstName) Then
MsgBox "First name cannot be blank", vbOKOnly
Me.txtFirstName.SetFocus
isFormValid = False
ElseIf IsNull(Me.txtLastName) Then
MsgBox "Last name cannot be blank", vbOKOnly
Me.txtLastName.SetFocus
isFormValid = False
End If
End Function
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Not isFormValid Then
Cancel = 1
End If
End Sub

VB 6.0 Add new record raises error object variable or With block not set

I want to add a new record to my database on the form load event - that is, as soon as my form loads the text box will be blank, which will enable the user to input info that will then be added to the database.
When my code is this, however:
Private Sub Form_Load()
Data1.Recordset.AddNew
End Sub
I keep getting an error:
run-time error '91'; object variable or With block not set.
what should I do?
place your code in Form_Initialize()
Private Sub Form_Initialize()
Data1.Recordset.AddNew
End Sub
I think; You need to change it to something like this:
Private Sub Form_Load()
Dim rs As ADODB.Recordset
Set rs = Data1.Recordset
rs.AddNew
rs!Column1 = 1
rs!Column2 = "test
rs.Update
End Sub
Now, If you have the error message over Set rs = Data1.Recordset then we need to know what is Data1.
Just add adodc1.refresh before addnew line. It will solve it.

How to pass value to SQL Query in Data Environment's Command Object at run-time in Visual Basic 6.0?

In DataEnvironment I have a Command Object in which I have
given following SQL Query:
SELECT * FROM userdetails WHERE Date = Todays_date
Here Todays_date is a public variable in Module.
This variable accepts value at run-time.
How to call variable in DataEnvironment's SQL Query?
The VB6 manuals cover this in Closing and Reopening the Recordset under the heading Data Environment Programming Guidelines. The example given there looks like:
Option Explicit
Private Sub Command1_Click()
' You must close the recordset before changing the parameter.
If DataEnvironment1.rsCommandQuery.State = adStateOpen Then
DataEnvironment1.rsCommandQuery.Close
End If
' Reopen the recordset with the input parameter supplied by
' the TextBox control.
DataEnvironment1.CommandQuery Text1.Text
With Text2
.DataField = "AU_LName"
.DataMember = "CommandQuery"
Set .DataSource = DataEnvironment1
End With
End Sub
Private Sub Form_Load()
' Supply a default value.
Text1.Text = "172-32-1172"
' Change the CommandButton caption.
Command1.Caption = "Run Query"
End Sub
You call the Command object as a method of its parent DataEnvironment, passing the parameters there. Gotta love The Fine Manual.

Resources