Is there a way to match class properties at runtime in VBA? - excel

I'm trying to match an obtained property from one class with another class's same property at run time. After some research, I found out that there is such thing as "Reflection" in .net but Im using just VBA. Just for background: I'm automating an application using this code, so some objects are exposed, while others are not.
The way I'm currently doing it is using a property of obtained class "Description", and use that to search for the same property at the targeted class.
Set TargetVar = hySetOperations.Item(j).TargetVariable 'This is a RealVariable a property that refers to a class
Set SourceObj =hySetOperations.Item(j).SourceObject 'This is also a RealVariable
'In order to import variable from source object, we r gonna use TargetVariable description and truncate space, and use it (This might not work if description
'is different than actual name of the variable)
Dim RealVarString As String
RealVarString = TargetVar.Description
'Trim spaces
RealVarString = Replace (RealVarString, " ", "")
Set SourceVar = CallByName ( SourceObj, RealVarString, vbGet)
This actually works for most of the cases since "description" is usually the same as property's name, but with spaces. However, in some cases, this is not the case, in which things go south.

Related

Worksheet.Columns property asks me for a RowIndex?

If I write this in the VBA editor:
Dim ws As Worksheet: set ws = ActiveSheet
ws.Columns(
IntelliSense shows me a seemingly unrelated tooltip:
_Default([RowIndex], [ColumnIndex])
The Worksheet.Columns property only accepts the index (column) number as far as I can see in the documentation.
So why am I asked for a RowIndex? Why does it refers to _Default (and what is it)?
The Worksheet.Columns property only accepts the index (column) number as far as I can see in the documentation.
Nowhere in the documentation does it say the Columns property takes a parameter, and indeed, it would be wrong to mention that, because it doesn't have any:
Like Worksheet.Rows, Worksheet.Columns yields a Range object. So when you "parameterize" it, what's really happening is this:
Set foo = ws.Columns.[_Default](value)
Any argument you provide, get interpreted as arguments to an implicit default member call against the Range object that was returned by the call to Columns.
You may have read somewhere that the default member of a Range is its Value - and that is not true. The default member of a Range is a hidden property named [_Default] (square brackets are required in VBA if you want to invoke it explicitly, because no legal VBA identifier can begin with an underscore), that takes two optional parameters:
When you read ("get") this default property without providing any arguments, this default property does get you the Range.Value (i.e. a single Variant value for a single cell, or a 2D Variant array for multiple cells). When you assign to this default property, you are assigning the Range.Value.
But when any arguments are provided when reading ("get") this default property, what you get is a call to the very standard Range.Item indexer property:
So what Columns does, is simply take your input range, and yield a Range object laid out in such a way that it can be accessed using a RowIndex argument - we can prove this using named arguments, which show that this code is illegal:
?Sheet1.Range("A1:C1").Columns.Item(ColumnIndex:=2).Address
>> "wrong number of arguments"
As is this equivalent code:
?Sheet1.Range("A1:C1").Columns(ColumnIndex:=2).Address
>> "error 1004"
Note that the _Default property yields a Variant, so the above .Address member call can only be resolved at run-time (and you don't get any intellisense for it, and the compiler will not flinch at any typo, even with Option Explicit specified - you will get error 438 at run-time though).
Best stick to safe early-bound land, and pull the returned object reference into a local variable:
Dim foo As Range
Set foo = ws.Columns(1)
Debug.Print foo.Address '<~ early-bound w/intellisense & compile-time validation
TL;DR: You're being prompted for a RowIndex argument because you are making a call (albeit an implicit one) to a hidden _Default property that accepts a RowIndex argument.

V93k test method parameter names with forbidden Ruby characters

The custom V93K test methods we use have parameter names that have characters that are forbidden in Ruby. For example:
testmethodparameters
tm_1:
"ComponentRule.ComponentRuleNameVariable" = "ComponentRuleMinConfig";
"ComponentRule.ExecuteRules" = "true";
"ComponentRule.RuleGroupNameVariable" = "ComponentRuleGroupName";
"ComponentRule.ScriptNameVariable" = "ComponentRuleScriptName";
"Softset.NumberOfPatternInfo" = "1";
"Softset.PatternInfo0.EdgesPerVector" = "2";
When looking at the Origen V93k docs, I see that Origen will convert a Ruby styled variable to the camel case required by the V93k, but would it handle a variable with an actual period in it? I am storing them using the Origen::Parameters::Set class like so, but to retrieve the correct parameter name, I would have to write some 'parameter name flattener' method.
params.bist.Softset.PatternInfo0.EdgesPerVector = "2"
params.bist.Softset.PatternInfo0.FuseProgramming = "false"
Before I write said method, does Origen already have a way to handle this case already that is not part of the docs? If not, would a PR be well received?
thx
It would handle a period in the C++ parameter name, the example here contains a parameter called 'An.UnusualName'.
When you supply the parameter name via a string like this then it is rendered verbatim into the test flow:
tm_1:
"An.UnusualName" = "blah"
To assign a value to this in an interface though then you need to convert the period to an underscore, Origen will create both the fully lower-cased and underscored accessor and also one with only the periods converted to underscores:
t = test_methods.my_lib.my_test
t.an_unusual_name = "blah"
t.An_UnusualName # => "blah"
It would add significant complication to generate filler objects on the fly to support t.An.UnusualName = "blah" and I don't think it is worth it - the existing API is fine for humans.
I can see that supporting the name with the period might be preferable for scripting though.
An easier approach that would provide what is needed would be to add a set_param method or similar to this class:
t.set_param("An.UnusualName", "blah")

VBA Access Arguments Passing Values

Access 2013
I'm calling a formula to modify a string and it's changing the values w/in the parent sub.
Example:
Debug.Print Str 'Hello World my name is bob
BOBexists = InStringChceck(Str,"bob")
Debug.Print Str 'HELLO WORLD MY NAME IS BOB
Debug.Print BOBexists 'TRUE
I've used this function, InStringCheck, in Excel VBA before (and it's just an example, all of my string tools are doing this same thing now and I don't know why)
Function InStringCheck(Phrase as string, Term as string) as Boolean
Phrase = UCase(Phrase)
Term = UCase(Term)
if instr(1, Phrase, Term) then InStringCheck = True else InStringCheck = False
end function
In several of my functions I manipulate the input variables, to arrive at a solution, but I don't want those manipulations to persist outside of the function unless I pass them back up - some how they're being passed up, but they're not dimed as public variables
VBA parameters are implicitly passed by reference (ByRef). This means you're passing a reference to the value, not the value itself: mutating that value inside the procedure will result in that mutated value being visible to the calling code.
This is often used as a trick to return multiple values from a function/procedure:
Public Sub DoSomething(ByVal inValue1 As Integer, ByRef outResult1 As Integer, ...)
You have two options:
Pass the parameters by value (ByVal)
Introduce local variables and mutate them instead of mutating the paramters (and heck, pass the parameters ByRef explicitly)
If you have lots of occurrences of parameters being implicitly passed ByRef in your project, fixing them everywhere can easily get tedious. With Rubberduck you can easily locate all occurrences, navigate there, and apply appropriate fixes:
Disclaimer: I'm heavily involved in the Rubberduck project.
Building a little on #Sorcer's answer, VBA has default Sub/Functions parameters passing "by reference" (i. e.: "ByRef" keyword assumed if not specified) so that if you don't want their "inside" modifications survive outside them you have to explicitly type "ByVal" keyword before them in the arguments list.
But you have the option to avoid such modifications take place altoghether by using StrComp():
Function InStringCheck(Phrase as string, Term as string) as Boolean
InStringCheck = StrComp(Phrase, Term, vbTextCompare) = 0
End Function
Which could also lead you to avoid the use of InStringCheck() in favour of a direct use of StrComp() in your code

writing an excel formula with multiple options for a single parameter

I would like to access information from a HTTP based API and manipulate it with excel.
The API returns about 20 pieces of information, and you can get that information by looking up any number of about ten lookup fields: name, serial number etc.
I want to write a function similar to the Match Function in excel where one of the parameters (in this case MATCH TYPE) has multiple possible values.
I have a list of values (the 20 pieces of information the API can return) and I want to make these pieces of information the possible return values for one of the Functions parameters.
How do I do I create a function where one parameter has a list of possible values?
And how do I add tooltip help statements to those parameter options so people know what they are?
You want to use an Enum.
In the declarations part of your module (before any subs or functions) you can place code like this.
Enum MyFunctionsArgValue
LessThan
Equal
GreaterThan
End Enum
This will assign each of these keywords an integer value, starting at zero and counting up. So LessThan = 0, Equal = 1, and GreaterThan = 2. (You can actually start at any number you want, but the default is usually fine.)
Now you can use it in your function something like this.
Function MySuperCoolFunction(matchType as MyFunctionsArgValue)
Select Case matchType
Case LessThan
' do something
Case Equal
' do it different
Case GreaterThan
' do the opposite of LessThan
End Select
End Function
To get the tool tip, you need to use something called an Attribute. In order to add it to your code, you'll need to export the *.bas (or *.cls) file and open it in a regular text editor. Once you've added it, you'll need to import it back in. These properties are invisible from inside of the VBA IDE. Documentation is sketchy (read "nonexistent"), so I'm not sure this works for an Enum, but I know it works for functions and module scoped variables.
Function/Sub
Function MySuperCoolFunction(matchType as MyFunctionsArgValue)
Attribute MySuperCoolFunction.VB_Description = "tool tip text"
Module Scoped Var
Public someVar As String
Attribute someVar.VB_VarDescription = "tooltip text"
So, you could try this to see if it works.
Enum MyFunctionsArgValue
Attribute MyFunctionsArgValue.VB_VarDescription = "tool tip text"
LessThan
Equal
GreaterThan
End Enum
Resources
https://www.networkautomation.com/automate/urc/resources/help/definitions/Sbe6_000Attribute_DefinintionStatement.htm
http://www.cpearson.com/excel/CodeAttributes.aspx

VBA: Use a variable as a reference to a user defined type

How can I reference a user defined type using a local variable without creating a copy of the type instance?
As an example, in the code below what I would ideally like to do is in MySub3 where I create a local variable, MT, and reference a data structure nested inside another struct ... but VBA doesn't allow this. It allows it for objects but not for user defined types (arrggg!) ... and for no apparent reason ... it just doesn't allow it.
MySub1 shows how to reference the nested struct in a long clunky way.
MySub2 shows how to do this by passing in the nested struct, but this clutters up the calling routine, and having multiple such nested structs gets ugly.
MySub2 demonstrates that VBA can do what I want, it just doesn't seem to provide a way to do it. I'm hoping there is a method I just haven't stumbled upon.
Note that my actual code is MUCH more complicated than this example, with multiple independent structs providing indices to many arrays as struct elements. Using these local reference variables would make the code much more readable and manageable.
Also Note that I am aware of the "with" statement, and it does help, but can only be used on one struct at a time.
Also Note that I am aware that I could use an actual object class. My code started out using an object but I quickly found out that VBA places limitations on arrays as property members ... a limitation that user defined types don't have.
Type tMyType
VariableA As Single
End Type
Type tMyOtherType
MyTypeArray() As tMyType
End Type
Type tOneMoreType
MyOtherType As tMyOtherType
End Type
Dim GlobalIndex As Integer
Sub TopLevel()
Dim TopLevelType As tOneMoreType
ReDim TopLevelType.MyOtherType.MyTypeArray(0 To 10)
Call MySub1(TopLevelType)
Call MySub2(TopLevelType.MyOtherType.MyTypeArray(GlobalIndex))
Call MySub3(TopLevelType)
End Sub
Sub MySub1(OMT As tOneMoreType)
Dim VarA As Single
VarA = OMT.MyOtherType.MyTypeArray(GlobalIndex).VariableA
End Sub
Sub MySub2(MT As tMyType)
Dim VarA As Single
VarA = MT.VariableA
End Sub
Sub MySub3(OMT As tOneMoreType)
Dim VarA As Single
Dim MT
Set MT = OMT.MyOtherType.MyTypeArray(GlobalIndex)
VarA = MT.VariableA
End Sub
From my point of view you have made it vary complicated. But I believe you have the reason for that.
The example you submitted generate the error you mentioned. But, when I changed some lines there is no error. I am not sure if my suggestion is the result you expected (while the question isn't fully clear to me) but try this instead of your MySub3:
Sub MySub3(OMT As tOneMoreType)
Dim VarA As Single
Dim MT
MT = OMT.MyOtherType.MyTypeArray(GlobalIndex).VariableA
VarA = MT
End Sub
Generally, this way I'm able to read any element im MySub3 passed from TopLevel.
If it is not the answer please clarify more.
I think here you have hit one of the limitations of VBA. I know of no way round the limitation on partial dereferencing of nested user types.
I think you would be best using classes containing private arrays with getter and setter functions (sadly, VBA doesn't have operator overloading either).

Resources