Defining cross-module variables with values - excel

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.

Related

WorkbookOpen event sometimes not firing - event used for set global variables

I have a really basic problem with my projects and I would like to know which approach is the best. I like to use (hated) globals, only for a few the most important objects in a workbook.
I am declaring e.g. my data tables in a such way:
'#Folder("Main")
Option Exclicit
Public tblDatabase As Listobject
Public tblReport As Listobject
Sub setMyTables()
Set tblDatabase = wsDatabase.ListObjects("tDatabase")
Set tblReport = wsReport.ListObjects("tReport")
End Sub
In the past I used this macro before actions on the table, e.g.:
Function getIdFromDatabaseTable() As Variant
' set variable-object to use
setMyTables <-- I used to table-setting-sub in every
macro which requires one of my table
' get ID from table
Dim arr As Variant
arr = tblDatabase.ListColumns("ID").DataBodyRange.Value2
' assign array to function result
getIdFromDataTable = arr
End Function
But why I had to begin almost every macro with calling setMyTables() macro? So I've started to use workbook open event to set my object variables:
[code in ordinary Module]
'#Folder("Main")
Option Exclicit
Public tblDatabase As Listobject
Public tblReport As Listobject
And call setMyTables() macro in Workbook_Open() event code. And here my problem is:
[TLTR] Setting variable-objects in Workbook-Open event seems unrielable. It seems it is not firing sometimes. I am sure that no macro error would reset the project and 'clear' already set variables, because sometimes it throws error on the very first macro run. It is not working occasionally and I don't know what pattern behind it is, I send Excel workbooks to my clients, and it's hard to debug what's realy going on there.
Additional comments
I've just read that this could happen if file is not in trusted localizations, I would like get to know best approach to handle declaring the most used objects globally (if possible without modifying someones trusted folders or another local-PC settings).
I know that I can set a 'flag' bool variable such as wasWorkbookOpenEventFired, but I would have to call checking function or make ifs on almost every Sub or Function in a workbook. So I think it isn't good solution too. Thanks for hints!
You'd have more robust results if you define public functions which each return a specific table, and use those instead of global variables:
Function DatabaseTable() As ListObject
Static rv As ListObject '<< cache the table here
'if your code gets reset then this will just re-cache the table
If rv Is Nothing then Set rv = wsDatabase.ListObjects("tDatabase")
Set DatabaseTable = rv
End Function

Call helper function within parent without redefining objects from parent in the helper

I'm working in Excel with VBA to collect data for a table I'm building I have to go out to a TN3270 emulator to get it. In order to work with with the emulator I have to define a few objects to do the work. I also have a few helper functions that are used by multiple functions to navigate to different screens in the emulator. So far in order to use them I have had to copy the object definitions into those functions to get them to work. This works most of the time but occasionally (and in a way I cant predictably replicate) I get an error when the helper is recreating a particular object to use.
Option Explicit
Public Sub gather_data()
Dim TN_Emulator As Object
Dim Workbook As Object
Set TN_Emulator = CreateObject("TN_Emulator.Program")
Set Workbook = ActiveWorkbook
Dim string_from_excel As String
#for loop to go through table rows
#put value in string_from_excel
If string_from_excel = some condition
go_to_screen_2
#grab and put data back in excel
Else
go_to_screen_3
#grab and put data back in excel
End If
go_to_screen_1
#next loop logic
End Sub
Public Sub go_to_screen_1()
Dim TN_Emulator As Object
#the next step occasionally throws the error
Set TN_Emulator = CreateObject("TN_Emulator.Program")
#send instructions to the emulator
End Sub
Is there a way to import the existing objects (that get created and used without any errors) without redefining them into the helper functions to avoid this problem? I have tried searching in google but I don't think I'm using the right search terms.
First thanks goes to #JosephC and #Damian for posting the answer for me in the comments.
From JosephC 'The Key words you're looking for are: "How to pass arguments to a function".', and he provided the following link ByRef vs ByVal describing two different ways to pass arguments in the function call.
And from Damian the solution to my immediate concern. Instead of declaring and setting the objects that will be used in body of the helper function. Place the object names and types in the parentheses of the initial helper name, and when calling the helper from the other function also in the parentheses, shown below.
Option Explicit
Public Sub gather_data()
Dim TN_Emulator As Object
Dim Workbook As Object
Set TN_Emulator = CreateObject("TN_Emulator.Program")
Set Workbook = ActiveWorkbook
Dim string_from_excel As String
#for loop to go through table rows
#put value in string_from_excel
If string_from_excel = some condition
Call go_to_screen_2(TN_Emulator)
#grab and put data back in excel
Else
Call go_to_screen_3(TN_Emulator)
#grab and put data back in excel
End If
Call go_to_screen_1(TN_Emulator)
#next loop logic
End Sub
Public Sub go_to_screen_1(TN_Emulator As Object)
#send instructions to the emulator
End Sub
I believe I understood the instructions correctly, and have successfully tested this for my-self. I also passed multiple objects in the helper function definition and calls as needed for my actual application, in the same order each time Ex.
Sub go_to_screen_1(TN_Emulator As Object, ConnectionName As Object)
and
Call go_to_screen_1(TN_Emulator, ConnectionName)

MS Access: Choosing Worksheet from Excel Workbook

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

Only user-defined type defined in public object modules can be coerced when trying to call an external VBA function

I am trying to call an Access function from Excel and get this error:
Compile Error: Only user-defined types defined in public object
modules can be coerced to or from a variant or passed to late-bound
functions.
I tried to adopt this solution I found, but with no luck. Here is my code:
In the Excel Module ExternalStatistics
Option Explicit
Public Type MyExternalStatistics
esMyInvites As Single
esMyInvitePerTalk As Single
End Type
Public MyExtRecStats As MyExternalStatistics
In the Sheet1(A-Crunched Numbers) object:
Option Explicit
Public appRecruitingAccess As Access.Application
Public Sub Worksheet_Activate()
Dim MyExtRecStats As MyExternalStatistics
Dim RecruitWindow As Integer
Dim test As String
Set appRecruitingAccess = New Access.Application
With appRecruitingAccess
.Visible = False
.OpenCurrentDatabase "C:\Dropbox\RECRUITING\Remote0\Recruiting 0.accdb"
RecruitWindow = DateDiff("d", Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveStart").Value), Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveEnd").Value))
RecruitWindow = DateDiff("d", Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveStart").Value), Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveEnd").Value))
MyExtRecStats = .Run("ExternalRecruitingStats", RecruitWindow) '*** ERROR HERE ***
.CloseCurrentDatabase
.Quit
End With
Set appRecruitingAccess = Nothing
End Sub
In the Access Module ExternalStatistics
Option Compare Database
Option Explicit
Public Type MyExternalStatistics
esMyInvites As Single
esMyInvitePerTalk As Single
end Type
Public Function ExternalRecruitingStats(StatWindow As Integer) As MyExternalStatistics
Dim MyRecStats As MyExternalStatistics
Dim Invites As Integer, Talks As Integer
Invites = 1
Talks = 2
With MyRecStats
.esMyInvites = CSng(Invites)
.esMyInvitesPerTalk = CSng(Invites/Talks)
End With
ExternalRecruitingStats = MyRecStats 'return a single structure
End Function
It does not like the MyExtRecStats = .Run("ExternalRecruitingStats", RecruitWindow) statement. I would like to eventually assign several set in the Access function and bring them all back with one object. Then I can place those values where they should be in the spreadsheet.
Type definitions in VBA are very local and they don't work well when you try to use them with objects that may not have access to the exact definition of the Type (which is probably the case here).
Sometimes, using a Class may work. You would need to make the class public and instantiate it before passing it around, but I have some doubts that it will actually work (for the same reason that the class definition won't be visible from one app to the other).
Another simple solution would be to use a simple Collection object instead, where you add your values as items to the collection. Of course the exact order of how you add/retrieve items is important.
There are a few interesting answers to a similar issue in User Defined Type (UDT) As Parameter In Public Sub In Class Module. It's about VB6 but it should also apply in great part to VBA.
Having said all this, you may be able to resolve all your issues by importing your Access code into Excel instead.
You can use DAO or ADO from Excel and manipulate Access databases just as if you were in Excel, for instance:
Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model
Using Excel VBA to Export data to Ms.Access Table

String declaration error in if else

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

Resources