VBA pass variables between Sub and Public Function - excel

I'm new to VBA and am trying to pass a string from a Sub to a Public Function (the Sub and Public Function are in separate modules but the same Workbook), split the string into an array in the Public Function, then pass the array back to the Sub from the Public Function.
I've searched though Stack Overflow and tried several different methods but they haven't worked. Below is the code I currently have which produces the following error:
Run-time error '9':
Subscript out of range
Any help would be appreciated. Apologies for the basic question. Thank you.
Sub:
Sub export()
Dim testString As String
Dim testValue As Variant
'testString could have any number of values
testString = "TEST1, TEST2, TEST3, TEST4"
'Call the Public Function below
testValue = splitText(testValue)
End Sub
Which calls the following Public Function in another module:
Public Function splitText() As Variant
Dim testValue As Variant
'Trying to import testString from the Sub to split it
testValue = Split(testString, ",")
'Define result of the Public Function
splitText = testValue
End Function

You need to use consistent variable names and pass argument in function call
Public Sub export()
Dim testString As String
Dim testValue As Variant
testString = "TEST1, TEST2, TEST3, TEST4"
testValue = splitText(testString) '<== consistent naming and passed as argument
End Sub
Public Function splitText(ByVal testString As String) As Variant '<== argument referenced in function signature
Dim testValue As Variant
testValue = Split(testString, ",") '<== consistent naming
splitText = testValue
End Function

Related

Error handling of multiple class attributes

I have a class that holds data in separate attributes (I chose this design instead of an array or scripting.dictionary because I will be using these data for the construction of a decision tree and I want to make use of IntelliType while I construct it.).
The data are loaded from an excel spreadsheet in the form of floats, so I am storing them in a long datatype, but from time to time it happens so that a value is missing and is replaced by an "NA" string.
I would like to create an error-handling routine, that, if a non-numeric value is encountered, would replace the content with a value -1.
I know I could do this with checking with IsNumeric() or error-handling, but I don't know how to make it work for every one of the many attributes the class holds and I don't really like the solution to write a specific error-handling code for every one of them (storing each of them in a separate attribute is not elegant as well, but I find this a price I am willing to pay for the advantage of shorter syntax in the decision tree).
Is there a way to pass a value to a variable, that just encountered a type-mismatch error, by the error-handling code independent of the variable name?
A simple example with several of the attributes:
Option Explicit
Dim B_LYM As Long
Dim B_mem As Long
Dim B_CXCR3 As Long
Dim B_CXCR4_MFI As Long
Public Sub SetData(data as Range)
On Error Goto err_handler
B_LYM = data.Cells(1, 1)
B_mem = data.Cells(1, 2)
B_CXCR3 = data.Cells(1, 3)
B_CXCR4_MFI = data.Cells(1, 4)
err_handler:
'I need something like this:
'if valuebeingstored = "NA" then targetvariable = -1
End Sub
It could be that some other approach could be better and I am gladly open to options, I only want to emphasize that I would really like make use of IntelliType when constructing the decision tree. I was considering using scripting.dictionary, but the syntax will bloat the code very quickly.
You said you have a Class and therefore could include the function to check the input and return -1 inside the class and use the Get and Let properties to call the function.
Here is an example class (named clsDataStuff) demonstrating this:
Option Explicit
Private c_B_LYM As Double
Private c_B_mem As Double
Private c_B_CXCR3 As Double
Private c_B_CXCR4_MFI As Double
Public Property Let B_LYM(varValue As Variant)
c_B_LYM = ParseDouble(varValue)
End Property
Public Property Get B_LYM()
B_LYM = c_B_LYM
End Property
Public Property Let B_mem(varValue As Variant)
c_B_mem = ParseDouble(varValue)
End Property
Public Property Get B_mem()
B_mem = c_B_mem
End Property
Public Property Let B_CXCR3(varValue As Variant)
c_B_CXCR3 = ParseDouble(varValue)
End Property
Public Property Get B_CXCR3()
B_CXCR3 = c_B_CXCR3
End Property
Public Property Let B_CXCR4_MFI(varValue As Variant)
c_B_CXCR4_MFI = ParseDouble(varValue)
End Property
Public Property Get B_CXCR4_MFI()
B_CXCR4_MFI = c_B_CXCR4_MFI
End Property
Private Function ParseDouble(varValue As Variant) As Double
If IsNumeric(varValue) Then
ParseDouble = CDbl(varValue)
Else
ParseDouble = -1
End If
End Function
Noting that:
the Let property expects a Variant because you say your input could be a number, or a string
the Get property returns Double as you said your inputs are floats so Double is better than Long
the ParseDouble function simply checks for a numeric input and returns -1 otherwise
Then, in your module code:
Option Explicit
Dim B_LYM As Long
Dim B_mem As Long
Dim B_CXCR3 As Long
Dim B_CXCR4_MFI As Long
Public Sub Test()
Dim objDataStuff As clsDataStuff
Set objDataStuff = New clsDataStuff
objDataStuff.B_LYM = 1 'data.Cells(1, 1)
objDataStuff.B_mem = 2 'data.Cells(1, 2)
objDataStuff.B_CXCR3 = "a" 'data.Cells(1, 3)
objDataStuff.B_CXCR4_MFI = True 'data.Cells(1, 4)
Debug.Print objDataStuff.B_LYM
Debug.Print objDataStuff.B_mem
Debug.Print objDataStuff.B_CXCR3
Debug.Print objDataStuff.B_CXCR4_MFI
End Sub
Returns an output of:
1
2
-1
-1
Intellisense is available and you get validation of the input:
Edit - regarding the comment on dynamically setting a target variable.
Your class can be:
Option Explicit
Public B_LYM As Double
Public B_mem As Double
Public B_CXCR3 As Double
Public B_CXCR4_MFI As Double
Public Sub SetVar(ByVal strVarName As String, ByVal varValue As Variant)
Dim dblValue As Double
Dim strToEval As String
If Not MemberExists(strVarName) Then Exit Sub
dblValue = ParseDouble(varValue) ' do the parse
CallByName Me, strVarName, VbLet, dblValue ' dynamically assign the value
End Sub
Private Function ParseDouble(varValue As Variant) As Double
If IsNumeric(varValue) Then
ParseDouble = CDbl(varValue)
Else
ParseDouble = -1
End If
End Function
Private Function MemberExists(strVarName) As Boolean
Dim blnTest As Boolean
Dim varValue As Variant
On Error GoTo ErrHandler
varValue = CallByName(Me, strVarName, VbGet)
blnTest = True
GoTo ExitFunction
ErrHandler:
blnTest = False
ExitFunction:
MemberExists = blnTest
End Function
Where:
All the variables are Public and you still get Intellisense but avoid all the repetitive Let and Get code
A single SetVar method uses CallByName to dynamically set a target variable
Two problems:
You need the clunky MemberExists function to prevent SetVar trying to assign a value to a member that does not exist - otherwise this generates an error (438) but perhaps this is something you need in your logic ?
You can still assign values to the target variable with e.g. objDataStuff.B_CXR3 = "foo" which alsos produces an error for anything other than a number.
The example code shows the problem below. But sticking with SetVar method will produce the same output as above.
Option Explicit
Dim B_LYM As Long
Dim B_mem As Long
Dim B_CXCR3 As Long
Dim B_CXCR4_MFI As Long
Public Sub Test()
Dim objDataStuff As clsDataStuff
Set objDataStuff = New clsDataStuff
objDataStuff.SetVar "B_LYM", 1
objDataStuff.SetVar "B_mem", 2
objDataStuff.SetVar "B_CXCR3", -1
objDataStuff.SetVar "B_CXCR4_MFI", True
objDataStuff.SetVar "foobar", 999
' working around SetVar here generates an error
objDataStuff.B_CXCR3 = "bad"
Debug.Print objDataStuff.B_LYM
Debug.Print objDataStuff.B_mem
Debug.Print objDataStuff.B_CXCR3
Debug.Print objDataStuff.B_CXCR4_MFI
End Sub

Passing parameter into function to create variable name

I want to use global variables in my workbook and in the ThisWorkbook code. I declared the following varaibles
Public position_1 as string
Public position_2 as string
If I want to see the value of those variables I believe they need to be fully qualified so
Debug.Print ThisWorkbook.position_1
Debug.Print ThisWorkbook.position_2
I have written a UDF which I will pass in an integer to represent which variable I am looking for. I will only be passing in a single number and not a full variable name. I am trying to find a way to use this integer to concatenate with "position_" to display the value of the global variable, ThisWorkbook.position_1, ThisWorkbook.position_2, etc.
Function Test_Global_Var(position as Integer)
Dim variable_name As String
variable_name = "position_" & position
Debug.Print ThisWorkbook.variable_name
End Function
So when I call
Test_Global_Var(1)
my immediate window should display the value of
ThisWorkbook.position_1
The code below produces the following debug output
2 values defined.
ThisWorkbook.Position(0)
First Value
ThisWorkbook.Position(1)
Second Value
It uses a private array in the workbook named m_position. The contents are accessed by a global property ThisWorkbook.Position(index).
In a module have the following code:
Option Explicit
Public Sub Test()
If ThisWorkbook.NoValues Then
ThisWorkbook.FillValues "First Value", "Second Value"
End If
Debug.Print CStr(ThisWorkbook.Count) & " values defined."
Test_Global_Var 0
Test_Global_Var 1
End Sub
Public Sub Test_Global_Var(ByVal index As Long)
' Part of a UDF
Debug.Print "ThisWorkbook.Position(" & CStr(index) & ")"
Debug.Print ThisWorkbook.Position(index)
End Sub
In ThisWorkbook have the following code:
Option Explicit
Private m_position() As Variant
Private Sub Workbook_Open()
Call DefaultValues
End Sub
Public Property Get Position(ByVal index As Long) As Variant
Position = m_position(index)
End Property
Public Sub DefaultValues()
m_position = Array("First", "Second")
End Sub
Public Sub FillValues(ParamArray args() As Variant)
m_position = args
End Sub
Public Property Get Count() As Long
Count = UBound(m_position) - LBound(m_position) + 1
End Property
Public Property Get NoValues() As Boolean
On Error GoTo ArrUndefined:
Dim n As Long
n = UBound(m_position)
NoValues = False
On Error GoTo 0
Exit Sub
ArrUndefined:
NoValues = True
On Error GoTo 0
End Property
PS. In VBA never use Integer, but instead use Long. Integer is a 16bit type, while Long is the standard 32bit type that all other programming languages consider as an integer.
It is possible to consider a global dictionary variable and pass data through it from the UDF.
First add reference to Microsoft Scripting Runtime:
Thus, build the dictionary like this:
Public myDictionary As Dictionary
To initialize the myDictionary variable, consider adding it to a Workbook_Open event:
Private Sub Workbook_Open()
Set myDictionary = New Dictionary
End Sub
Then the UDF would look like this:
Public Function FillDicitonary(myVal As Long) As String
If myDictionary.Exists(myVal) Then
myDictionary(myVal) = "position " & myVal
Else
myDictionary.Add myVal, "position " & myVal
End If
FillDicitonary = "Filled with " & myVal
End Function
And it would overwrite every key in the dictionary, if it exists. At the end, the values could be printed:
Public Sub PrintDictionary()
Dim myKey As Variant
For Each myKey In myDictionary
Debug.Print myDictionary(myKey)
Next
End Sub

Excel 2010 vba array as a class member error

I am working on a project and have run into something that I don't understand. When assigning an array to a class member, the Let and Get names cannot be the same. If they are, I get the error:
Definitions of property procedures for the same property are inconsistent, or property procedure has an optional parameter, a ParamArray, or an invalid Set final parameter
Can anyone tell me if I'm just doing something wrong, or if this is just how it is. The code below generates the above message.
Test Code:
Sub loadServer()
Dim testServer As AvayaServer
Dim i As Long
Dim arr() As Variant
arr = Array("1", "2", "3", "4", "5")
Set testServer = New AvayaServer
testServer.Name = "This Sucks"
testServer.Skill = arr
MsgBox testServer.Skills(4)
MsgBox testServer.Name
End Sub
Class Code:
Private pName As String
Private pSkills() As String
Public Property Get Skills() As Variant
Skills = pSkills()
End Property
Public Property Let Skills(values() As Variant)
ReDim pSkills(UBound(values))
Dim i As Long
For i = LBound(values) To UBound(values)
pSkills(i) = values(i)
Next
End Property
Change values() As Variant to values As Variant:
Class Code:
Private pName As String
Private pSkills() As String
Public Property Get Skills() As Variant
Skills = pSkills()
End Property
Public Property Let Skills(values As Variant) 'Fixed here
ReDim pSkills(UBound(values))
Dim i As Long
For i = LBound(values) To UBound(values)
pSkills(i) = values(i)
Next
End Property
Explanation:
values As Variant will be of type Variant, which you later use to store an array.
values() As Variant is an array of type Variant, to which an Array cannot be assigned; an Array can only be assigned to the former.

Class Object Not Recognized

I'm having an issue with a class object not being recognized (error 91, object reference not set). Here's the code:
---Main (Standard Module)
Option Explicit
Public wbCode As Workbook
Public Sub MainSub()
Dim str As String
Dim tables As New CTables
Call SetExcelObjects
str = tables.shExclusions.Cells(20, 1) ---this produces error 91
End Sub
Public Sub SetExcelObjects()
Dim tables As New CTables
Dim str As String
Set wbCode = ThisWorkbook
Set tables.shExclusions = wbCode.Worksheets("Exclusions")
str = tables.shExclusions.Cells(20, 1) ---this line executes okay
End Sub
---CTables (Class Module)
Option Explicit
Public shExclusions As Worksheet
Try this:
---Main (Standard Module)
Option Explicit
Public wbCode As Workbook
Public Sub MainSub()
Dim str As String
Dim tables As New CTables
Call SetExcelObjects(tables)
str = tables.shExclusions.Cells(20, 1) ---this produces error 91
End Sub
Public Sub SetExcelObjects(tables as CTables)
Dim str As String
Set wbCode = ThisWorkbook
Set tables.shExclusions = wbCode.Worksheets("Exclusions")
str = tables.shExclusions.Cells(20, 1) ---this line executes okay
End Sub
---CTables (Class Module)
Option Explicit
Public shExclusions As Worksheet

VBA: Creating session persistent objects (hash) in Excel

Is it possible in a VBA function (UDF) to create an object that has global scope? I.e persists beyond the runtime of the function? I would want to stick it in a hash with a unique key that I can pass to other functions. I know you can do this in c#/c++ dll's.
The motivation is a heavy duty piece of processing that I don't want to repeat across hundreds of function calls: I want to cache the results so I only need to do once. E.g let's imagine I have a UDF which builds the results object in Cell A1:
=CreateResultsObject(arg1, arg2, arg3...)
The function does the heavy work and returns a unique ID string (the key for the object stored in the persistent hash). Cell A1 now contains this string value which I can then pass to other functions: they can then access the cached object in the hash with the key.
Is this possible? If so how?
The variables you declare in a module are persistent.
This code in a module might go into the direction you want:
Option Explicit
Dim col As New Collection
Public Function GetValue(ByVal strName As String) As String
GetValue = col.Item(strName)
End Function
Public Sub SetValue(ByVal strName As String, ByVal strValue As String)
col.Add strValue, strName
End Sub
Note:
For duplicate or missing names the code will fail.
Instead of a string value any kind of object could be passed by modifying the function signatures accordingly.
Addendum:
The same code with a bit more intelligence - for existing keys in the collection the value will be replaced instead of failing with an error.
Option Explicit
Dim col As New Collection
Public Function GetValue(ByVal strName As String) As String
GetValue = col.Item(strName)
End Function
Public Sub SetValue(ByVal strName As String, ByVal strValue As String)
If HasValue(strName) Then
col.Remove (strName)
End If
col.Add strValue, strName
End Sub
Private Function HasValue(ByVal strName As String) As Boolean
Dim val As Variant
Dim bRes As Boolean
bRes = True
On Error Resume Next
val = col.Item(strName)
If Err.Number <> 0 Then
bRes = False
Err.Clear
End If
On Error GoTo 0
HasValue = bRes
End Function
What about using a global variable within a module?
Something like this:
Option Explicit
Dim sHash As String
Function CreateResultsObject()
'very long code
sHash = "MyTest"
CreateResultsObject = "ok"
End Function
Function displayresultsobject()
displayresultsobject = sHash
End Function
Note that your Hash will be recalculated only when you call CreateResultsObject() in your worksheet and each time you ask for recalculation.

Resources