Addin Function, reference active worksheet - vba

I have created an addin which has 1 ribbon control, which performs a SQL statement on an Access DB and pastes the result, one cell to the right. This works perfectly. It is called SubTest(c as iribboncontrol) I also have another sub, called GetData(arg1,arg2) which I intended to use from the worksheet, as =GetData("01/02/2016","Open") and then one to the right again, the customised SQL returned is presented. This all works ok, until the pasting ActiveCell.Offset(1, 1).CopyFromRecordset rstData works fine from the ribbon, but not from the function call, am I missing something simple.
Having get data, like so, still gives errors
public sub get_data()
activecell.offset(1,1).value="TEST"
end sub
Many thanks

A function takes inputs and returns a value. It cannot have side-effects1. Hence, you can't call a procedure that alters cell values inside a function that's called from a worksheet cell, as Scott Craner already mentioned.
There are a number of things that are wrong with this though:
Public Sub get_data()
ActiveCell.Offset(1,1).Value="TEST"
End Sub
Code that relies on ActiveCell means you have other code that uses Select and Activate. This makes your code extremely frail and error/bug prone, avoid them (see how).
Avoid underscores in procedure names; use PascalCase instead. This isn't just "because it's convention" - VBA will refuse to compile more advanced code that has underscores in interface member names; so even if you don't ever use interfaces and the Implements keyword, make it a habit to avoid underscores in member names. In VBA the underscore has a special meaning, such as you can see in event handler procedures: ObjectName_MemberName, e.g. Button1_Click.
Name things for what they do. "get data" would be the name of a function, that "gets" a value [and returns it]. A Sub that "gets" something makes no sense. Your procedure doesn't "get" anything, it "sets" a value if anything.
1 Function procedures called from VBA code can definitely have side-effects. The fact is, in an ideal world they shouldn't; use procedures for side-effecting code instead. Excel worksheet functions are pure functions, and user-defined functions are required to be more or less pure functions as well, else they simply can't be used in a worksheet. Take some input, compute a value, return that value: that's all a function does.

Related

Is it possible to work with return types of Windows API function calls in Visual Basic? 3 questions [duplicate]

I've not seen this in other languages but I see it a lot in VBA (which I just started working with). Suppose you have a table in Word and wish to set the rows to a certain height. If you do this
tbl.Rows.SetHeight InchesToPoints(1), wdRowHeightExactly
the table's rows indeed are set to 72 points or 1 inch in height. However, if you surround the arguments in parentheses, something I did instinctively, VBA gives an error -- expected:=.
I can solve this by using a throw-away variable, like this
x = tbl.Rows.SetHeight (InchesToPoints(1), wdRowHeightExactly)
or, of course, I can simply not surround the arguments in parentheses.
Microsoft's documentation on the SetHeight method doesn't mention any return value, but in any case, this behavior is extensive throughout VBA. It's not specific to the SetHeight method.
My questions: What is this called? Should I use a throw-away variable or throw away the parentheses? What's the logic from Microsoft's point of view? Are there consequences to using one or the other, consequences I can't imagine (because they are unknown unknowns)?
Definitely don't introduce a "throw-away variable", especially if it's not declared, and especially if what you're invoking is a Sub, a procedure that doesn't return any value. Well you can, if you don't mind a compile-time error:
Expected Function or variable.
Now...
this behavior is extensive throughout VBA. It's not specific to the SetHeight method.
#Yoe3k put it nicely:
As for what it is called, I would guess "correct syntax" is the most appropriate word.
That's the whole answer: it's not about SetHeight, it's about how VBA's implicit procedure/member call syntax works. The explicit Call syntax has been obsolete since the wonderful advent of implicit calls, about a quarter of a century ago. So splattering Call keywords left & right and all over your code will, indeed, keep you the parentheses... if you hold them so dear.
But the "logic" of the implicit call syntax isn't all that complicated, really.
What follows is what I wrote on Documentation.SO about VBA and parentheses, hope it helps.
This is confusing. Why not just always use parentheses?
Parentheses are used to enclose the arguments of function calls. Using them for procedure calls can cause unexpected problems.
Because they can introduce bugs, both at run-time by passing a possibly unintended value to the procedure, and at compile-time by simply being invalid syntax.
Run-time
Redundant parentheses can introduce bugs. Given a procedure that takes an object reference as a parameter...
Sub DoSomething(ByRef target As Range)
End Sub
...and called with parentheses:
DoSomething (Application.ActiveCell) 'raises an error at runtime
This will raise an "Object Required" runtime error #424. Other errors are possible in other circumstances: here the Application.ActiveCell Range object reference is being evaluated and passed by value regardless of the procedure's signature specifying that target would be passed ByRef. The actual value passed ByVal to DoSomething in the above snippet, is Application.ActiveCell.Value.
Parentheses force VBA to evaluate the value of the bracketed expression, and pass the result ByVal to the called procedure. When the type of the evaluated result mismatches the procedure's expected type and cannot be implicitly converted, a runtime error is raised.
Compile-time
This code will fail to compile:
MsgBox ("Invalid Code!", vbCritical)
Because the expression ("Invalid Code!", vbCritical) cannot be evaluated to a value.
This would compile and work:
MsgBox ("Invalid Code!"), (vbCritical)
But would definitely look silly. Avoid redundant parentheses.
The most serious consequence of using parentheses inappropriately can best be demonstrated by code such as:
Sub Test()
Dim r As Range
Set r = Range("A1")
TestSub r
TestSub (r)
End Sub
Sub TestSub(parm As Range)
MsgBox parm.Address
End Sub
In that code TestSub r correctly passes a range object to TestSub. However, placing parentheses around the r, i.e. TestSub (r) causes VBA to evaluate r using its Value property and is therefore equivalent to TestSub r.Value. This then gives an error as it is passing a Variant (maybe a Variant/Double with a value of 123.45) to a subroutine that is expecting a Range.
It is basically just incorrect syntax to enclose parameters to a Subroutine within parentheses. They should only be used when a Function is returning a value.
P.S. I apologise that my example is Excel VBA. I hadn't noticed that the question was Word VBA, plus I could knock up an Excel example quicker than I could research Word VBA enough to give an example in it. The principle is the same in both though.

Passing arguments from Visio ShapeSheet to procedure in VBA

I have been working with Visio VBA for a couple of years. I pass arguments from the ShapeSheet of a shape to several procedures in VBA using either RUNMACRO() or CALLTHIS() Functions.
I either pass pass plain strings or the value of different formulas in the ShapeSheet. The most common argument that I pass to my procedures is the ID() of the shape.
After a patch update of Windows: https://support.microsoft.com/en-us/topic/march-15-2021-kb5001566-os-build-18363-1441-out-of-band-23c4c824-8638-43e9-a381-ff58213ae6fe, I am no longer able to pass arguments from the ShapeSheet of a Shape to my procedures in VBA. Whenever I use RUNMACRO or CALLTHIS, all the arguments that I pass, even if they are plain strings, in my procedure side everything that I get is "", blank information.
Is there a way to know if this is a bug or if this is on purpose, maybe as a security measure?
Here is a simple example procedure:
Public Function HelloWorld(Number As Integer)
If Number = 1 Then
MsgBox ("Hello World 1")
End If
If Number = 2 Then
MsgBox ("Hello World 2")
End If
End Function
And this procedure is called in the EventDblClick of a Shape:
RUNMACRO("HelloWorld(1)","Test")
When the EventDblClick is triggered the value of Number stays as null, ignoring the argument sent in the RUNMACRO function, which is a 1. Since the argument of Number in the HelloWorld() function is not optional, it triggers a Compile error message
"Argument not optional"
My programs were also recently affected by this update. Previously, I was able to structure the ‘macroname’ string in RUNMACRO (macroname [,projname_opt]) to include arguments to my functions and subroutines (as in Alexis’ HelloWorld example). However, that suddenly seems to be no longer possible. It is almost as if RUNMACRO is now modifying the ‘macroname’ string to exclude any arguments prior to making the call to the Function or Subroutine.
One workaround that I have found is to use CALLTHIS and restructure the VBA Function or Subroutine slightly as shown below. That said, it is going to be a huge hassle for me to execute this change in every cell, in every shape, in every file using the RUNMACRO formula. I’m going to have to write a separate macro just to execute this change.
Workaround:
CALLTHIS(HelloWorld,,1)
[NOTE: The two commas are intentional.]
Public Function HelloWorld(callingShape as Visio.Shape, number as Integer)
‘Insert Code Here
End Function

What is behind this difference in parentheses effect in VBA?

I've not seen this in other languages but I see it a lot in VBA (which I just started working with). Suppose you have a table in Word and wish to set the rows to a certain height. If you do this
tbl.Rows.SetHeight InchesToPoints(1), wdRowHeightExactly
the table's rows indeed are set to 72 points or 1 inch in height. However, if you surround the arguments in parentheses, something I did instinctively, VBA gives an error -- expected:=.
I can solve this by using a throw-away variable, like this
x = tbl.Rows.SetHeight (InchesToPoints(1), wdRowHeightExactly)
or, of course, I can simply not surround the arguments in parentheses.
Microsoft's documentation on the SetHeight method doesn't mention any return value, but in any case, this behavior is extensive throughout VBA. It's not specific to the SetHeight method.
My questions: What is this called? Should I use a throw-away variable or throw away the parentheses? What's the logic from Microsoft's point of view? Are there consequences to using one or the other, consequences I can't imagine (because they are unknown unknowns)?
Definitely don't introduce a "throw-away variable", especially if it's not declared, and especially if what you're invoking is a Sub, a procedure that doesn't return any value. Well you can, if you don't mind a compile-time error:
Expected Function or variable.
Now...
this behavior is extensive throughout VBA. It's not specific to the SetHeight method.
#Yoe3k put it nicely:
As for what it is called, I would guess "correct syntax" is the most appropriate word.
That's the whole answer: it's not about SetHeight, it's about how VBA's implicit procedure/member call syntax works. The explicit Call syntax has been obsolete since the wonderful advent of implicit calls, about a quarter of a century ago. So splattering Call keywords left & right and all over your code will, indeed, keep you the parentheses... if you hold them so dear.
But the "logic" of the implicit call syntax isn't all that complicated, really.
What follows is what I wrote on Documentation.SO about VBA and parentheses, hope it helps.
This is confusing. Why not just always use parentheses?
Parentheses are used to enclose the arguments of function calls. Using them for procedure calls can cause unexpected problems.
Because they can introduce bugs, both at run-time by passing a possibly unintended value to the procedure, and at compile-time by simply being invalid syntax.
Run-time
Redundant parentheses can introduce bugs. Given a procedure that takes an object reference as a parameter...
Sub DoSomething(ByRef target As Range)
End Sub
...and called with parentheses:
DoSomething (Application.ActiveCell) 'raises an error at runtime
This will raise an "Object Required" runtime error #424. Other errors are possible in other circumstances: here the Application.ActiveCell Range object reference is being evaluated and passed by value regardless of the procedure's signature specifying that target would be passed ByRef. The actual value passed ByVal to DoSomething in the above snippet, is Application.ActiveCell.Value.
Parentheses force VBA to evaluate the value of the bracketed expression, and pass the result ByVal to the called procedure. When the type of the evaluated result mismatches the procedure's expected type and cannot be implicitly converted, a runtime error is raised.
Compile-time
This code will fail to compile:
MsgBox ("Invalid Code!", vbCritical)
Because the expression ("Invalid Code!", vbCritical) cannot be evaluated to a value.
This would compile and work:
MsgBox ("Invalid Code!"), (vbCritical)
But would definitely look silly. Avoid redundant parentheses.
The most serious consequence of using parentheses inappropriately can best be demonstrated by code such as:
Sub Test()
Dim r As Range
Set r = Range("A1")
TestSub r
TestSub (r)
End Sub
Sub TestSub(parm As Range)
MsgBox parm.Address
End Sub
In that code TestSub r correctly passes a range object to TestSub. However, placing parentheses around the r, i.e. TestSub (r) causes VBA to evaluate r using its Value property and is therefore equivalent to TestSub r.Value. This then gives an error as it is passing a Variant (maybe a Variant/Double with a value of 123.45) to a subroutine that is expecting a Range.
It is basically just incorrect syntax to enclose parameters to a Subroutine within parentheses. They should only be used when a Function is returning a value.
P.S. I apologise that my example is Excel VBA. I hadn't noticed that the question was Word VBA, plus I could knock up an Excel example quicker than I could research Word VBA enough to give an example in it. The principle is the same in both though.

Excel VBA store functions or subroutines in an array

In C/C++, when I have a bunch of functions (pointers), I can store them in an array or a vector and call some of them together in a certain order. Can something similar be done in VBA?
Thanks!
Yes, but I don't recommend it. VBA isn't really built for it. You've tagged this question with Excel, so I will describe how it is done for that Office Product. The general concept applies to most of the Office Suite, but each different product has a different syntax for the Application.Run method.
First, it's important to understand the two different methods of dynamically calling a procedure (sub/function) and when to use each.
Application.Run
Application.Run will either run a subroutine or call a function that is stored in a standard *.bas module.
The first parameter is the name of the procedure (passed in as a string). After that, you can pass up to 30 arguments. (If your procedure requires more than that, refactor for the love of code.)
There are two other important things to note about Application.Run.
You cannot use named arguments. Args must be passed by position.
Objects passed as arguments are converted to values. This means you could experience unexpected issues if you try to run a procedure that requires objects that have default properties as arguments.
Public Sub Test1()
Application.Run "VBAProject.Module1.SomeFunction"
End Sub
The takeaway:
Use Application.Run when you're working with a standard module.
VBA.Interaction.CallByName
CallByName executes a method of an object, or sets/gets a property of an object.
It takes in the instance of the object you want to call the method on as an argument, as well as the method name (again as a string).
Public Sub Test2()
Dim anObj As SomeObject
Dim result As Boolean
result = CallByName(anObj, "IsValid")
End Sub
The takeaway:
Use CallByName when you want to call a method of a class.
No pointers.
As you can see, neither of these methods use actual pointers (at least not externally). They take in strings that they then use to find the pointer to the procedure that you want to execute. So, you'll need to know the exact name of the procedure you want to execute. You'll also need to know which method you need to use. CallByName having the extra burden of requiring an instance of the object you want to invoke. Either way, you can stores these names as strings inside of an array or collection. (Heck, even a dictionary could make sense.)
So, you can either hard code these as strings, or attempt to extract the appropriate procedure names at runtime. In order to extract the procedure names, you'll need to interface with the VBIDE itself via the Microsoft Visual Basic for Applications Extensibility library. Explaining all of that here would require far too much code and effort, but I can point you to some good resources.
Articles & SE Questions:
Chip Pearson's Programming The VBA Editor
Extending the VBA Extensibility Library
Ugly workaround to get the vbext_ProcKind is breaking encapsulation
Automagic testing framework for VBA
How to get the procedure or function name at runtime
Import Lines of Code
Meta Programming in VBA: The VBIDE and Why Documentation is Important
The code from some of my Qs & As:
vbeCodeModule
vbeProcedure
vbeProcedures
A workaround is to enumerate and use a switch statement. You can store enumerated types (longs) in an array. E.g.:
Enum FType
func1
func2
func3
End Enum
Sub CallEnumFunc(f As FType, arg As String)
Select Case f
Case func1: MyFunction1(arg)
Case func2: MyFunction2(arg)
Case func3: MyFunction3(arg)
End Select
End Sub
Dim fArray(1) As FType
fArray(0) = func1
fArray(1) = func2
CallEnumFunc fArray(1), "blah"

Should I use Call keyword in VB/VBA?

I use the Call keyword when calling subs in VB/VBA. I know it's optional, but is it better to use it or leave it off? I've always thought it was more explicit, but maybe it's just noise.
Also, I read this on another forum: Using the Call keyword is faster because it knows that it is not going to return any values, so it doesn't need to set up any stackspace to make room for the return value.
Ah ha. I have long wondered about this and even reading a two inch thick book on VBA basically says don't use it unless you want to use the Find feature of the VBE to easily find calls in large projects.
But I just found another use.
We know that it's possible to concatenate lines of code with the colon character, for example:
Function Test(mode as Boolean)
if mode = True then x = x + 1 : Exit Sub
y = y - 1
End Sub
But if you do this with procedure calls at the beginning of a line, the VBE assumes that you're referring to a label and removes any indents, aligning the line to the left margin (even though the procedure is called as intended):
Function Test()
Function1 : Function2
End Function
Using the Call statement allows concatenation of procedure calls while maintaining your code indents:
Function Test()
Call Function1 : Call Function2
End Function
If you don't use the Call statement in the above example, the VBE will assume that "Function1" is an label and left align it in the code window, even though it won't cause an error.
For VB6, if there is any chance it will be converted to VB.NET, using Call means the syntax doesn't change. (Parentheses are required in VB.NET for method calls.) (I don't personally think this is worth the bother -- any .NET converter will at least be able to put in parentheses when required. I'm just listing it as a reason.)
Otherwise it is just syntactic sugar.
Note the Call keyword is likely not to be faster when calling some other method/function because a function returns its value anyway, and VB didn't need to create a local variable to receive it, even when Call is not used.
I always use Call in VBA. To me, it just looks cleaner. But, I agree, it's just syntactic sugar, which puts it squarely the realm of personal preference. I've come across probably a dozen full time VBA guys in the past few years, and not one of them used Call. This had the added advantage that I always knew which code was mine. :p
No, it'll just add 7 characters per call with no given benefit.
No one covered this important distinction: in some (common) situations, Call prevents parentheses around function (and sub) arguments from causing the arguments to be strictly interpreted as ByVal.
The big takeaway for you is that if you DO use parentheses around arguments to a routine, perhaps by rote or habit, even though they are not required, then you SHOULD USE Call to ensure that the routine's implicit or explicit ByRef is not disregarded in favor of ByVal; or, instead, you should use an "equal sign" assignment of the return value to prevent the disregard (in which case you would not use Call).
Again, that is to protect you from unfavorably getting ByVal from a routine. Conversely, of course, if you WANT ByVal interpretation regardless of the routine's declaration, then LEAVE OFF the Call (and use parentheses).
Rationale: summarizing "ByRef and ByVal Parameters"
If
1. there is an assignment of a function call retval, e. g.
iSum = myfunc(myArg)
or
2. "Call" is used, e. g.
call myFunc(myArg)
or
call mySub(myArg)
then the parentheses strictly delineate the calling argument list; the routine declaration determines ByVal or ByRef. OTHERWISE the parentheses force ByVal to be used by the routine - even though ByVal was not specified in the routine. Thus,
mySub(myArg) 'uses ByVal regardless of the routine's declaration, whereas
Call mySub(myArg) 'uses ByRef, unless routine declares ByVal
Also note that Call syntactically mandates use of parentheses. You can go
mySub myArg
but you can't go
call mySub myArg
but you CAN go
call mySub(myArg)
(and parentheses are syntactically required for assignment of Function return value)
NOTE however that ByVal on the routine declaration overrides all of this. And FYI, ByRef is always implied in the declaration if you are silent; thus TMK ByRef has no apparent value other than documentary.
Repeating from above: The big takeaway for you is that if you DO use parentheses around arguments to a routine, perhaps by rote or habit, even though they are not required, then you SHOULD USE Call to ensure that the routine's implicit or explicit ByRef is not disregarded in favor of ByVal; or, instead, you should use an "equal sign" assignment of the return value to prevent the disregard (in which case you would not use Call).
Again, that is to protect you from unfavorably getting ByVal from a routine. Conversely, of course, if you WANT ByVal interpretation regardless of the routine's declaration, then LEAVE OFF the Call (and use parentheses).
I use Call for all VBA development of common library functions that I possibly will use in VB.NET. This allows me to move code using copy and paste between all the flavors of VB. I do this to avoid the syntax errors that the code editor creates when it "formats" or "pretty prints" the pasted code. The only edits are usually Set statement inclusion/exclusion.
If you have no plans to move your VB/VBA code to VB.NET, then there is no need to use the Call statement.
The only case I found "call" is useful is quite an accident, about some special operators.
Dim c As IAsyncOperation(Of StartupTask) = StartupTask.GetAsync("Startup")
……
(Await c).Disable()
I got a syntax error for the second line, just like what you'll get with a "New" operator. I really don't want a new variable, which is too inelegant for me. So I tried:
DirectCast(Await c, StartupTask).Disable()
This is syntactically correct. But then the IDE hinted me that the "DirectCast" is unnecessary and gave a simplification. Yes, that is:
Call (Await c).Disable()
That's why I love VS2017 Preview. 😄
If you read the MSDN Support page for the Call Statement, for the specific case o VBA, at least, it does say that Call is optional, but what is very relevant about it and nobody seems to notice is this quoted line:
"If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded."
This is why Call is far from useless. Say you're writing Sub SupportTasks that does a lot of very relevant stuff for you Main Subs (for example, it imports data from a file to be used by different procedures). Now, notice that since SupportTasks is reading external data, there's always a fat chance this data will not come standard and the sub will not be able to fulfill its role. What do you do?
You could, for example, use boolean functions that return False if something goes wrong. Instead of calling a sub, call a function SupportTasks inside and If statement that will exit the Main sub if there's an anomaly:
If Not SupportTasks(SomeArgument) Then
Application.ScreenUpdating = True
Exit Sub
'Else continue the Main sub regularly without writing anything in here
End If
If you're wondering what the heck this has to do with Call, consider the following: in another sub, I call SupportTasks, but I do not need its returned boolean value (for instance, I'm certain an error won't occur). Well, if I don't put it in an If statement or assign the function to a useless variable, VBA will not compile and return me an error (procedure call invalid blah blah blah must assign value to something blah blah blah). That's where Call comes in to save the day!
Call SupportTasks(SomeArgument) '<< "Call Function" call doesn't return an error
If you still think it's useless, think of it as a resource to stay organized. Writing separate procedures for routines shared by many procedures makes your code shorter and more comprehensible, specially when you're writing really large applications. ERPs built out of Excel-Access integrations, for example, can be easier to operate, repair and customize if your IT dept slow to deliver/implement the real system...
To conclude, some internet wisdom:
Always write your code as if the person who will review it is a murderous psychopath who knows where you live.
Amen.
I'm 7 years late to the party, but I just happened to come across the Call keyword a few minutes ago while reading something on MSDN. In particular, it was used to do something I thought was impossible in VB.NET (as opposed to C#) -- which is related to #FCastro's answer.
Class Test
Public Sub DoSomething()
Console.WriteLine("doing something")
End Sub
End Class
Sub Main()
Call (New Test()).DoSomething()
End Sub
In the odd case you don't need the actual object instance but require one of its methods, you can use Call to save a line. Note that this is unnecessary when it's the right-hand side of an operation:
Class Test
Public Function GetSomething() As Integer
Return 0
End Function
End Class
Sub Main()
Dim x As Integer = (New Test()).GetSomething()
End Sub