I have a form which have referenced to previous form variable in the following code. I have change the scope to Public for the variable WorkflowName, however, error still happened.
Form 1:
Option Compare Database
Option Explicit
Public WorkflowName As String
Private Sub btn_CreditControlEmail_Click()
WorkflowName = "Email to Credit Control"
DoCmd.OpenForm "WorkFlow Email Preview"
End Sub
Form 2:
Option Compare Database
Dim frmPrevious As Form
Dim WorkflowName As String
Private Sub btn_ToOutlook_Click()
'update workflow status to Renewal Table
MsgBox frmPrevious![WorkflowName]
End Sub
Private Sub Form_Load()
Set frmPrevious = Screen.ActiveForm
End Sub
However, when run to second form
MsgBox frmPrevious![WorkflowName]
The following error happened.
In watching the value of frmPrevious in second form, I can see the "WorkflowName" value of frmPrevious.
If you want to refere to a variable in another form you can't use frmPrevious![WorkflowName], because that refers to a field in the first form that does not exist.
But use this: a dot and without brackets:
MsgBox frmPrevious.WorkflowName
Edit:
Another way to do this, and get the Intelisense to work, is by using the Form_ syntax.
Lets say Form 1 is named "WorkflowStart"
MsgBox Form_WorkflowStart.WorkflowName
Related
I had a Run-time error
'-2147418105 (800100007)': Automation error The object invoked has disconnected from its clients.
which is raised once in a while. I can't relate it to a specific context for this error. The only clue I have is that before using ADO code I never had that error. The implemented pattern was used many times.
I use Excel 2016 32 bits on windows 7 with a vba code.
Private mForm As frmCfgPrjctTm
Public Sub U_CfgPrjctTm_OnOpen()
If (mForm Is Nothing) Then
Call U_UnlockTeam
Set mForm = New frmCfgPrjctTm
End If
'>>>>>> the error occurs after this comment
mForm.Show vbModeless
End Sub
The code to "close" the form is as following
Public Sub U_CfgPrjctTm_OnClose()
If (Not mForm Is Nothing) Then
mForm.Hide
Dim tmp As frmCfgPrjctTm
Set tmp = mForm
Set mForm = Nothing
Unload tmp
End If
End Sub
and in the form code (childCfgPrjctTmSettings and childCfgPrjctTmSettings are defined in an enum to falg a user action before closing the form)
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Call U_UnlockTeam
Select Case CloseMode
Case vbAppWindows, vbAppTaskManager
Call U_CfgPrjctTm_OnClose
Case vbFormControlMenu, vbFormCode
Call Save
Select Case mbOpenForm
Case childCfgPrjctTmSettings
' this opens another form
Call U_Sttngs_OnOpen(delUsr)
Case childCfgPrjctTmUsrId
' this opens another form
Call U_UsrLggd_OnOpen(dpyUsrLggdCfgPrjctTeam)
End Select
End Select
Cancel = False
End Sub
and in the form code
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Call U_UnlockTeam
Select Case CloseMode
Case vbAppWindows, vbAppTaskManager
Call U_CfgPrjctTm_OnClose
Case vbFormControlMenu, vbFormCode
Call Save
Select Case mbOpenForm
Case childCfgPrjctTmSettings
Call U_Sttngs_OnOpen(delUsr)
Case childCfgPrjctTmUsrId
Call U_UsrLggd_OnOpen(dpyUsrLggdCfgPrjctTeam)
End Select
End Select
Cancel = False
End Sub
This error is raised after creating a form and at the very moment to show it up.
The call U_UnlockTeam involves some ADO code called inside to retreive data from a data base. The form has no Activate event handler.
Did some one have the same issue and how did you cope with ?
I am able to reproduce the error. The issue is that you unload the form inside the form. Take just an empty userform and the following code in a module. Run the code and close the form by clicking on X. There should be no code behind the form! If you run the code a second time you will get the error mentioned.
Option Explicit
Private mForm As UserForm1
Public Sub U_CfgPrjctTm_OnOpen()
If mForm Is Nothing Then
'Call U_UnlockTeam
Set mForm = New UserForm1
End If
'>>>>>> the error occurs after this comment
mForm.Show vbModeless
End Sub
Reason of the behavior is that the class destroyed itself and mForm is a module wide variable which does not know it was destroyed when calling the code the second time.
Solution would be to avoid a self-destroing class/userform or as a workaround make mForm a local variable.
Here is a better explanation
https://excelmacromastery.com/vba-user-forms-1/#Cancelling_the_UserForm
It says I have too few parameters expected 15... It is something with my before and after refresh.
Class 1
Public WithEvents qt As QueryTable
Private Sub qt_AfterRefresh(ByVal Success As Boolean)
Application.Worksheets("RawDataLines").Range("A1") = Application.Worksheets("RawDataLines").Range("C1")
Application.Run "'Operation Get Ipads.xls'!Assembly1_Button"
End Sub
Class 2
Public WithEvents qut As QueryTable
Private Sub qut_BeforeRefresh(Cancel As Boolean)
Worksheets("RawDataLines").Range("C1") = _
"='H:\Departments\Manufacturing\Production Links\DashBoard Breakdown\[MASTER_LIVE_STATUS_DATA.xls]Sheet1'!R1C1"
If Application.Worksheets("RawDataLines").Range("C1") = Application.Worksheets("RawDataLines").Range("A1") Then
Cancel = True
End If
End Sub
Initialize:
Dim T As New Class1
Dim H As New Class2
Sub Initialize_It()
Set T.qt = ThisWorkbook.Sheets(3).QueryTables(1)
Set H.qut = ThisWorkbook.Sheets(3).QueryTables(1)
End Sub
Private Sub qt_BeforeRefresh(ByVal Success As Boolean)
the argument is usually Cancel and this is what your code refers to. Change it to Cancel.
You can refer to the current workbook (where this code is running) as ThisWorkbook. Assuming it is the MASTER one, then you can use:
ThisWorkbook.Worksheets("sheet1").Range("A1")
The Workbooks collection refers only to open workbooks, so you will need to temporarily open the other workbook:
Dim wbOther As Workbook
Set wbOther = Workbooks.Open("full path and filename.xlsx", False)
the False argument indicates that you do not wish to Update Links when opening the book (if appropriate).
When you have finished with the other book, use:
wb.Close False 'False says that you do not need to Save Changes
Set wb = Nothing
It is possible to get a single value from another workbook without opening and closing it, but if that book also has links this may cause an issue:
Debug.Print ExecuteExcel4Macro("'F:\Documents and Settings\student\My Documents\[AndysData7.xlsx]Staff List'!R6C4")
Note, the formula needs to use R1C1 notation. (Rather than Debug.Print you would store the value in a variable.) Note also that I am not necessarily recommending this approach, as it is undocumented, but thought I'd mention it in the context of the question.
I am new to VB.NET and WPF.
I am building a "Questionnaire" app. Users will be presented sequentially with different questions/tasks (windows). After they respond on each question/task and press a "submit" button a new window will open with a new question/task, and previous window will close. After each question, when the button is pressed, I need to store data to some global object. After all questions are answered the data of this object should be written out to the output file.
I figured out that Dictionary will be the best to store the results after each window.
I am not sure how, where to create this global Dictionary and how to access it. Should I use View Model? If yes, can you give an example? Or, should it be just a simple class with shared property? (something like this)
EDIT 2: I tried many different ways recommended online
GlobalModule:
Module GlobalModule
Public Foo As String
End Module
GlobalVariables:
Public Class GlobalVariables
Public Shared UserName As String = "Tim Johnson"
Public Shared UserAge As Integer = 39
End Class
Global properties:
Public Class Globals
Public Shared Property One As String
Get
Return TryCast(Application.Current.Properties("One"), String)
End Get
Set(ByVal value As String)
Application.Current.Properties("One") = value
End Set
End Property
Public Shared Property Two As Integer
Get
Return Convert.ToInt32(Application.Current.Properties("Two"))
End Get
Set(ByVal value As Integer)
Application.Current.Properties("Two") = value
End Set
End Property
End Class
Here is where I save the data to global variables/properties in the first window. I need to store data in this subroutine before closing an old window and opening a new window. I use MessageBox just for testing.
Private Sub btnEnter_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEnter.Click
Dim instructionWindow As InstructionsWindow
instructionWindow = New InstructionsWindow()
Application.Current.Properties("number") = textBoxValue.Text
Globals.One = "2"
Globals.Two = 3
MessageBox.Show("GlobalVariables: UserName=" & GlobalVariables.UserName & " UserAge=" & GlobalVariables.UserAge)
GlobalVariables.UserName = "Viktor"
GlobalVariables.UserAge = 34
GlobalModule.Foo = "Test Foo"
'testing if it saved tha value
'MessageBox.Show(Application.Current.Properties("number"))
Application.Current.MainWindow.Close()
instructionWindow.ShowDialog()
End Sub
Next subroutine is where I am trying to retrieve the value from global Properties/variables in the second window, but message boxes come out empty. There might also the case that I am assigning values in a wrong way, or not reading them in a right way (casting?) :
Private Sub FlowDocReader_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles FlowDocReader.Initialized
' Get a reference to the Application base class instance.
Dim currentApplication As Application = Application.Current
MessageBox.Show(currentApplication.Properties("number"))
MessageBox.Show("One = " & Globals.One & " Two = " & Globals.Two)
MessageBox.Show("GlobalVariables: UserName=" & GlobalVariables.UserName & " UserAge=" & GlobalVariables.UserAge)
MessageBox.Show("GlobalModule.Foo = " & GlobalModule.Foo)
Dim filename As String = My.Computer.FileSystem.CurrentDirectory & "\instructions.txt"
Dim paragraph As Paragraph = New Paragraph()
paragraph.Inlines.Add(System.IO.File.ReadAllText(filename))
Dim document As FlowDocument = New FlowDocument(paragraph)
FlowDocReader.Document = document
End Sub
Thanks.
You can make public Dictionary property for form and put your dictionry to this property or make constructor with Dictionary argument.
You already have this dictionary Application.Properties
Look here, please.
First, you can define a dictionary (list of lists) as follows at the beginning of a form or in a module
Dim dic As New Dictionary(Of String, List(Of String))
As the user completes questions on a form, write the partucular form number and query results to a single record in the dic before going to the next form (place this code into the "Next" button):
'Assume q1response=3, q2response=4,..., qpresponse="text", etc.
Dim myValues As New List(Of String)
myValues.Add(formname)
myValues.Add(q1response)
myValues.Add(q2response)
.
.
myValues.Add(qpresponse)
dic.Add(username, myValues)
When a user is done, there will be multiple records in the dictionary, each of which starts with their name and is followed by question responses. You can loop through multiple dictionary records, where each record is for a user using the following:
For Each DictionaryEntry In dic 'this loops through dic entries
Dim str As List(Of String) = DictionaryEntry.Value
'here you can do whatever you want with results while you read through dic records
'username will be = str(0)
'formname will be str(1)
'q1 response on "formname" will be str(2)
'q2 response on "formname" will be str(3)
'q3 response on "formname" will be str(4)
...
Next
The trick is that there will be multiple dictionary records with results for one user, where record one can have results like "John Doe,page1,q1,q2,q3" and record 2 will be "John Doe,page2,q4,q5,q6." Specifically, the "str" in the above loop will be an array of string data containing all the items within each dictionary record, that is, in str(0), str(1), str(2),... This is the information you need to work with or move, save, analyze, etc.
You can always put all the code I provided in a class (which will be independent of any form) and dimension the sic is a Sub New in this class, with the updating .Add values lines in their own sub in this same class). Then just Dim Updater As New MyNewClassName. Call the Updater in each continue button using Call Updater.SubNameWithAddValues(q1,q2,...qp). It won't matter where you are in your program since you using a specific class. The one thing I noticed with my code is that you can only use the line that adds the "key" or the username once, so use it after the last query -so put it in a Sub Finished in your new class and call as Call Updater.Finished(username,q30,q31,last)
I followed an example on stackoverflow about how to read database records into variables. This is the first time doing this and I feel that I'm close but I'm baffled at this point about the problem.
Here is the link I am referring to:
Visual Basic 2010 DataSet
My code is shown below.
Public Class Form1
' DataSet/DataTable variables
Dim testdataDataSet As New DataSet
Dim dttestdataDataTable As New DataTable
Dim datestdataDataAdapter As New Odbc.OdbcDataAdapter
' Variables for retrieved data
' Dim sSpeed As String = ""
' Dim sFuelprice As String = ""
Dim sSpeed As Integer
Dim sFuelprice As Integer
'Connect to the database
''
'Fill DataSet and assign to DataTable
datestdataDataAdapter.Fill(TestdataDataSet , "TestdataDataSet")
dttestdataDataTable = TestdataDataSet.Tables(0)
'Extract data from DataTable
' Rows is the row of the datatable, item is the column
sSpeed = dtTestdataDataTable.Rows(0).Item(0).ToString
sFuelprice = dtTestdataDataTable.Rows(0).Item(1).ToString
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
result.Text = Val(miles.Text) * sSpeed * sFuelprice
End Sub
End Class
Basically, I am getting declaration errors and I don't understand why since the example I was following clearly declared them. I'm connecting to an Access DB called "testdata.mdb" which contains only 1 record with two fields that I want to use throughout the program. The exanple said to dim the variables for each field as strings but this created more dim errors so I made them into integers and remarked out the original dim statements in the meantime (since they're going to be used in calculations.) The dataadapter and datatable variables also are getting flagged for not being declared when they were earlier in the program. I know this must be a simple thing to fix but I'm just not seeing it.
The form is just a simple thing where the user types in a number and a result is produced by using the numbers read in from the database. In short, I want to be able to do simple calculations with a database within a program and the dim statement thing is getting in the way.
If someone can please clarify what I should do, that would be very much appreciated. Thanks!
When you're trying to learn new technology, it's usually best to work from the outside in. The "outside-most" object in your case seems to be an OdbcConnection object.
Public Class Form1
Const connectionString as String = "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\bin\Northwind.mdb"
Dim connection As New OdbcConnection(connectionString)
connection.Open()
connection.Close()
end Class
Resolve errors at that level first. Then add a declaration for the data adapter--only for the data adapter--and resolve any errors with that. Repeat until you finish your class.
See OdbcConnectionString, and refer to the connection string web site if you need to.
I apologize for the delay in writing the answer to close off this question and sum it up.
In my case, it dataset is a one row database called testdata and contains 20 fields.
The solution that worked is as follows:
Immediately after the form1_load event, the variables can be immediately written after the dataadapter line:
Me.TestdataTableAdapter.Fill(Me.fooDataSet.testdata)
speed = Me.fooDataSet.testdata(0).speed
fuelprice = Me.fooDataSet.testdata(0).fuelprice
mpg = Me.fooDataSet.testdata(0).mpg
Then just DIM the variables to whatever you want them to be (in this case, speed is an integer, fuelprice is a decimal and MPG is a decimal) right after the PUBLIC CLASS statement at the top of your form's code.
You can then manipulate the variables in calculations after a button click as such:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
fuelcost = CDec((miles.Text/ mpg) * fuelprice)
txtfuelcost.Text = fuelcost.ToString
End Sub
Thank you all for your responses!
The title should give a fair overview of the problem but I'm running a dynamic named range for use in a combo box in a userform. When I run the form, the values appear as intended. When I call a module sub-routine via a command button, the values don't appear and I've no idea why.
I'll paste all code and highlight the offending snippet(s) below:
Private Sub btnGetGAToken_Click()
'--------------------------------
'Obtain API Token from Google Analytics (GA), indicate to user that token has been obtained and populate Account combobox
'with a unique list of accounts, which will in turn populate the Profile combobox with the profiles associated with the chosen
'account
'--------------------------------
Dim txtEmailField As String
Dim txtPasswordField As String
'Values written to sheet for use in UDFToken and UDFGetGAAcctData array formulas
Range("FieldEmail").Value = Me.txtEmailField.Text
Range("FieldPassword").Value = Me.txtPasswordField.Text
Range("GAToken").Calculate
With Me.lblGATokenResponseField
.Caption = Range("GAToken").Value
.ForeColor = RGB(2, 80, 0)
End With
Call FindUniqueAccountNames
cboAccountNamesComboBox.RowSource = Sheet1.Range("ListUniqueAccountNames").Address
End Sub
Private Sub cboAccountNamesComboBox_Change()
'Value written to sheet for use in the 'ListProfileNames' dynamic, named range
Range("ChosenAccount").Value = Me.cboAccountNamesComboBox.Value
With Me.cboProfileNamesComboBox
.Value = ""
.RowSource = Sheets("CodeMetaData").Range("ListProfileNames").Address
End With
End Sub
The dynamic range was created using the name manager and is below:
Named Range: "ListUniqueAccountNames" =OFFSET(CodeMetaData!$J$5,0,0,COUNTA(CodeMetaData!$J$5:$J$5000))
and for ease of reference, the code I'm using to run it is below:
cboAccountNamesComboBox.RowSource = Sheets("CodeMetaData").Range("ListUniqueAccountNames").Address
The sub-routine calling the userform is here:
Public Sub ShowReportSpecsForm()
Load frmReportSpecs
frmReportSpecs.Show
End Sub
Forgive me for posting so much of the code, but I'm not sure exactly what it is that's causing the problem - I'm still very much a rookie with forms.
Any help will be greatly appreciated. Thanks.
If you are using the rowsource property and named ranges then I would suggest setting the rowsource property of the combobox's at design time. Then to debug where required use:
Debug.Print Range("ListUniqueAccountNames").Address
This will return the named range address to the immediate window where you can check it is correct.
Remember that the property Address from a named dynamic range returns a normal static address.
For example, Range("ListUniqueAccountNames").Address can returns $J$5:$J$20.
You do not need use a Excel address in RowSource property. You can use a Excel name.
Besides, when you show a Userform it is necessary refresh the RowSource property from a ComboBox or ListBox control in order to update its values. (Excel control does not watch if the range or data change)
That refresh can be made inside Activate event (it runs immediately before form Show and it is shown below) and any situation where data or range changes.
Private Sub UserForm_Activate()
Me.cboAccountNamesComboBox.RowSource = ""
Me.cboAccountNamesComboBox.RowSource = "ListUniqueAccountNames"
End Sub