Dealing with end keyword in macros for array indices - metaprogramming

Suppose I have an array of a composite type as follows:
type myType
a::Int
b::Float
end
myArray=myType[]
For obvious reasons, I would like to be able to use simple indexing to access the fields of composite types as follows:
aVals=myArray[1:3].a
The following macro can successfully accomplish this type of indexing, as long as I have a numeric iterable for the array:
macro getArray(exp)
iter=eval(exp.args[1].args[2])
exp.args[1].args[2]=:i;
:[$(esc(exp)) for $(esc(:i)) in $iter]
end
How can I write a similar macro that is also capable of dealing with array indices with the end keyword, i.e.:
aVals=#getArray myArray[1:end].a

The following macro solves not only the indexing problem but also sets the correct output type:
macro getArray(exp)
quote
ftype=typeof($(esc(exp.args[1]))[1].($(esc(exp.args[2]))));
ftype[item.($(exp.args[2])) for item in $(esc(exp.args[1]))]
end
end

Related

Dictionary lookup fails

I am writing an Excel VBA program that validates a school course schedule. A key component is a global dictionary object that keeps track of the course number (the key) and the number of times that course is scheduled (the item). I have successfully created and loaded the dictionary. I'm trying to lookup the value associated with the course key, but have been unable to do so using the one-line examples I've found at this site. I'd like to use this line of code:
intCourseCnt = gdicCourses("BAAC 100")
or
intCourseCnt = gdicCourses.Item("BAAC 100")
but neither work (actually, the "BAAC 100" part is a string variable, but it won't even work if I hardcode a course in.) Instead, I have to use the kludgy loop code below to lookup the course count:
Private Function Check_Course_Dup_Helper(strCourse As String) As Boolean
Dim k As Variant
Check_Course_Dup_Helper = False
' Read thru dictionary. Look to see if only 1 occurrence then jump out.
For Each k In gdicCourses.Keys
If k = strCourse Then
If gdicCourses.Item(k) = 1 Then
Check_Course_Dup_Helper = True
Exit Function
End If
Exit Function
End If
Next
End Function
Is there a way to rewrite this so that I can lookup of the item value without the loop?
Thank you.
Thanks for the prompt replies. Answers below:
David, the gdicCourses("BAAC 100") code value while the program is running is "empty" which makes the receiving variable equal to 0. The result is the same if I use strCourse variable. Also, the dictionary populating code is shown below. I do not believe it is a problem because I can correctly access the values elsewhere in the program where For-Each-Next loops that use a range variable are employed. Whitespace and non-printable characters are not present.
My guess is that I need to use a range to reference the position in the dictionary rather than a string. I've tried pretty much every combination of this that I can think of, but the value is still "empty".
Set gdicCourses = New Scripting.Dictionary
For Each c In Worksheets("Tables").Range("combined_courses").Cells
If Not (gdicCourses.Exists(c)) Then
gdicCourses.Add c, (Application.WorksheetFunction.CountIF(Range("MWF_Table_Full"), c
(Application.WorksheetFunction.CountIf(Range("TTh_Table_Full"), c)))
End If
Next

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).

an efficient way acess a range in a user defined type?

I've got a user defined type with about 5000 entries. I would like to select a range of the data in about 1,000 entry blocks and use it as an array. Is there a way to do this without looping?
Something like
MyArray = MyType(1:1000).property
rather than
for i = 1 to 1000
MyArray(i) = MyType(i).property
Next i
Thanks!
No, there is no way to convert a collection of elements into an array without looping or special accessor methods for the type - let alone convert a common property from a collection of elements into an array.
The only objects that support anything like this are Range objects, for which you can convert certain properties of an array of cells (range) into an array using:
MyArray = Range("A1:A1000").Value
Again, nothing like this is available for other types unless the programmer goes through the trouble of defining the behaviour - and even if they did define it, odds are the method would likely include iterating over the elements anyways, just within the type class.

Resources