I'm writing some code in MS Access and I reached to the point where user needs to choose on which worksheet of an Excel workbook there need to be performed some operation. I don't know, what name of this worksheet is or on which position it is placed.
I was thinking about a solution which will show user a form (as modal form) with listbox containing all sheets names'. When user click one of them form will show aside A1:J10 range (so user can choose the right one worksheet). After confirming choosen worksheet it will return as worksheet object.
Every thing was great untill I wanted to pass a object variable to the form. In openArgs I can only pass a string. I was even thinking about a class which will open this form but it's still no luck with passing object parameter.
I'm trying to avoid global/public variables.
Any ideas?
Assuming your object is wsObj, can't you just use wsObj.Name ?
Also have a look at wsObj.CodeName, which may be interesting as well.
There are many possibilities to send some value between objects.
A) Using Global vars into ACCESS Vba module
Global yourvariable As String
if you need some different value can use Variant, Single, etc.
B) Using Windows Register
To save value:
SaveSetting "yourprojectname", "Settings", "yourvariable", yourvalue
To retrieve value:
retvalue = GetSetting("yourprojectname", "Settings", "yourvariable", "your_default_value_if_not_exist")
C) Using OpenArg into Open Form command procedure
DoCmd.OpenForm "stDocName", acNormal, "filter_if_needed", "stlinkcriteria", acFormEdit, acWindowNormal, "arguments_forOpenArgs"
On destination form
Private Sub Form_Open(cancel as integer)
your_args=Me.OpenArgs
On all three possible solutions you can send more than one value using a chain with vars and values, an example:
myvar_mutiple="name=John Doe|address=Rua del Percebe 34|location=Madrid|phone=34 91 1234567"
On this example i used "pipe" (AltGr on key 1) char to separate each var=value
Then on destination procedure only need split each pair:
splitvar=Split(myvar_multiple,"|")
With this you obtain for each "splitvar" an element like "name=John Doe"
Do again an split with "=" to obtain variable an value. For each value you can reassign the result to a local vars.
Full code example:
if me.OpenArgs<>"" then
splitvar=Split(me.OpenArgs,"|")
for x=0 to ubound(splitvar)
tmpsplit=Split(splitvar(x),"=")
paramvars=tmpsplit(0)
paramvalue=tmpsplit(1)
select case paramvars
case "name"
stname=paramvalue
case "address"
straddress=paramvalue
case "location"
strlocation=paramvalue
case "phone"
strphone=paramvalue
end select
next
end if
Some recommendations that i use for this code "multiple vars":
- always use Low Case variable or change this:
paramvars=tmpsplit(0)
by
paramvars=lcase(tmpsplit(0))
-if you need to use "=" into value you can change by other alternative char or search the first "=" form left (i used this solution instead Split)
paramvars=trim(lcase(left(splitvar(x),len(splitvar(x))-(len(splitvar(x))-instr(splitvar(x),"="))-1)))
remember that you can send any value and can be converted on destination code. On this sample i use only String so you can use cLng or cInt etc.
Over your solution to select Sheet on excel from Access i think there are better alternatives.
IN the forms Module you can declare a property as object and then set that property once loaded. So in the form module
Option Explicit
Private myObj as object
Property Set DesiredWorksheet(o as object)
set myobj = o
End
and then in your code
Load myform
set myform.desiredworksheet = wsObj
myform.show
Ahh, sorry I was writing Excel not Access!!!
Docmd.openform f
f.desiredworksheet = ws.obj
docmd.openform f, windowmode:=acdialog
ought to work
Related
Sub getTrailInfo()
Dim attr As Variant
Dim attrTB As String
attrNames = Split("trailName,trailType,aSideSite,zSideSite,status", ",")
Dim trailForm As New formTrailInfo
For Each attr In attrNames
attrTB = attr + "TB"
trailForm.attrTB = attr
Next attr
trailForm.Show
End Sub
When I run the above code it gives a compilor error: Method or Data not found at line trailForm.attrTB = attr
I have required variables in attrNames String array. I need to put values of these variables in corosponding textboxes in a userForm. The name of Text Box in this userForm is attrNameTB. For example Text box for trailName is trailNameTB.
You cannot use VBA like that.
When you start your code, the compiler will first compile the code and check that you want to access a property named attrTB of your form. This doesn't exist and you will get the error you mentioned.
The compiler cannot wait until your variable attrTB has an actual value and then guess that you don't want a property with that name, but use the content of that variable as property name.
However, every form has a collection of all it's controls (button, edit boxes, combo boxes, labels...), and you can access the members of a collection either by index or by name. As you have the name of the control in attrTB, you could simply write
trailForm.Controls(attrTB).Text = attr
I'm developing a bunch of Excel Macros for making my life easier. One part of different macros is inserting a picture into sheets. For this reason, I would like to save the path to the images in a global location and then access it via a variable (so that I don't have to manually adjust the paths in every macro if it changes). I use one module per macro
In my own module "Variables" I defined a variable as Public or Global and then assigned a value via a sub. If I now access this variable via another module, I get an empty MsgBox.
For test purposes I use a string which I want to display via an MsgBox.
Modul 1:
Public test As String
Sub variablen()
test = "String for Test "
End Sub
Modul 2:
Public Sub testpublic()
MsgBox (test)
End Sub
I recommend to use a constant instead of a variable:
Module 1
Option Explicit
Public Const MyPath As String = "C:\Temp"
Module 2
Option Explicit
Public Sub ShowPath()
MsgBox MyPath
End Sub
I also recommend to activate Option Explicit: In the VBA editor go to Tools › Options › Require Variable Declaration.
If you do it like you did test is empty until it was initialized by running the procedure variablen first. If you use Public Const no initialization is required.
so that I don't have to manually adjust the paths in every macro if it changes
If it ever needs to change, then it semantically isn't a Const. The key to writing code that you don't constantly need to modify is to separate the code from the data.
A file path that sometimes needs to change can be seen as some kind of configuration setting.
Have a module that is able to read the settings from wherever they are, and return the value of a setting given some key.
The settings themselves can live on a (hidden?) worksheet, in a ListObject table with Key and Value columns, and looked up with INDEX+MATCH functions (using the early-bound WorksheetFunction functions will throw run-time errors given a non-existing key string):
Option Explicit
Public Function GetSettingValue(ByVal key As String) As Variant
With SettingsSheet.ListObjects(1)
GetSettingValue = Application.WorksheetFunction.Index( _
.ListColumns("Value").DataBodyRange, _
Application.WorksheetFunction.Match(key, .ListColumns("Key").DataBodyRange, 0))
End With
End Function
The Variant will retain the subtype of the Value, so for a String value you get a Variant/String; for a Date value you get a Variant/Date, for a numeric value you get a Variant/Double, and for a TRUE/FALSE value you get a Variant/Boolean.
Now when the file path needs to change, your code does not:
Dim path As String
path = GetSettingValue("ImageFolderPath")
And if you need more settings, you have no code to add, either:
Dim otherThing As String
otherThing = GetSettingValue("OtherThing")
All you need to do is to make sure the string keys being used match the contents of the Key column in your SettingsSheet.
I developed a Form in Excel (2016) and I am trying (with VBA) to configure its behavior so that if the user selects a particular option button, two additional things happen:
A checkbox further down on the form is automatically checked.
A text box further down on the form automatically displays a set string of text.
More specifically, if the user selects OptionButtonABC, then ...
CheckBoxNone should become checked
TextBoxCompanyName (which does not display any text by default) should now display the string: 'ABC'.
I initially created a subroutine that just targeted condition 1, and everything worked fine. However, when I try to integrate the code required to handle condition 2, things start to unravel.
Below, you will see the code in its most current state. I have a Private Sub that initiates upon the Click event and then immediately defines a variable as a string. I then set up an if/then statement that specifies what should happen IF OptionButtonABC is true. Namely, CheckBoxNone should be selected (this works fine) AND TextBoxCompanyName should now display the string 'ABC'.
Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = ABC
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True And Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub
The desired behavior should (theoretically) be pretty easy to achieve, but my experience with VBA is still pretty limited, so I am reaching out to the community for a bit of advice. As I mentioned above, the code above works for the first condition. However, I am still unable to get the string of text ('ABC') to show up in the text box.
Thanks in advance for any advice you may offer.
Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = "ABC" 'String Values uses double quotes
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True
Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub
The operator AND must be used only in the IF statement comparison, not in what you want to do.
First post so I'll try my best to make it a good one (please tell me if I'm doing it wrong).I can't seem to write the code properly to change the value of a check box or option button on a sheet using a variable.
Suppose the name of the check box name is "Chk1", normally I would write :
Worksheets("AP-1").Chk1.value=X
Where X is (either True or False). Since it is a Loop, I use a range variable called FoundRange and it's value is the name of the check box, so I tried:
dim chkname as string
chkname=foundrange.value
Worksheets("AP-1").Chkname.value=X
I also tried
Worksheets("AP-1").CheckBoxes(chkname).Value = X
and
Worsheets("AP-1").Shapes(chkname).ControlFormat.Value=X
I also had a linked cell that I used to change the value, but when it writes either false or true in it, the check box becomes gray and I need to press F2+Enter in the linked cell to make the check box show the proper value. I also tried to select the linked cell after changing its value and use that code:
Application.SendKeys "{F2}"
Application.SendKeys "{ENTER}"
but it did not work.
Please help me :)
Based on your initial code, it must be an ActiveX control, not a Form one, so:
dim chkname as string
chkname=foundrange.value
Worksheets("AP-1").OLEObjects(Chkname).Object.value = X
I have Camp as string. When I write this code, I get an error:
*Me.BoatDesc =< the expression you entered refer to an object that is close*
Here is my code
private Sub Save_Click()
Dim Camp As String
If Me.BoatDesc = "Camp" Then
Me.Amount = Me.Amount * 12
End If
Correct me if I am wrong.
You are using VBA, not VB.Net. Here are some notes
Here is a simple form, it will be open when the code is run. The code will be run by clicking Save. Note that the default for an MS Access bound form is to save, so you might like to use a different name.
This is the form in design view, note that there is a control named BoatDesc and another named Amount, as can only be seen from the property sheet.
The save button have an [Event Procedure], which is the code.
Note that the code belongs to Form2, the form I am working with, and the words Option Explicit appear at the top. This means I cannot have unnamed variables, so it is much harder to get the names wrong.
This is the code to be run by the save button.
Option Compare Database
Option Explicit
Private Sub Save_Click()
''Do not mix up strings, variables, controls and fields
''If you want to know if a control, BoatDesc, equals
''the string "camp", you do not need this
''Dim Camp As String
If Me.BoatDesc = "Camp" Then
Me.Amount = Me.Amount * 12
End If
End Sub