Set a variable in one sub and use in another [duplicate] - vba

This question already has answers here:
How do I declare a global variable in VBA?
(9 answers)
Closed 9 years ago.
I am new to VBA programming and had a doubt which may be quite simple for you.
How do we set a variable in one sub which can be used in another?
I tried using global variable but it didnt work for me. Thank you

Here is an example of how I have created a variable in one sub and used it in another:
Private Sub txtLastName_LostFocus()
FirstName = Me.txtFirstName.Value
LastName = Me.txtLastName.Value
FullName = FirstName & " " & LastName
sayHelloToTheUser (FullName)
End Sub
Private Sub sayHelloToTheUser(name As String)
MsgBox "Hello " & name
End Sub
Essentially, you must pass it through using another sub and having it take the arguments that are necessary. This is the main way that I pass arguments through.

Related

Variable scope for a variable used in multiple userforms

I am trying to figure out how scope works.
For instance: I'm working on a userform in which a check procedure validates that new entries are not already present in the list. Because I'm probably going to use the full name (concatenation of first and last name) in different userforms within the same worksheet, I entered it as a Global variable in the general module:
Public Sub PublicVars()
Public FullName As String
End Sub
When I add the definition of the variable to the public sub, the check box does not work, but when I define it in the object in the userform, it does.
Private Sub cmbLastName_AfterUpdate()
FullName = cmbFirstName & " " & cmbLastName
If Application.WorksheetFunction.CountIf(Range("List_Full_Name"), FullName) Then
FullNameError = MsgBox("Name already included in contact list. Edit contact?", vbYesNo, "Error")
Else
End If
End Sub
This seems sensitive to mistakes, as when I want to use FullName for another object in the same userform or in a different userform in the same workbook, I would have to redefine it locally. I am probably overlooking something, as I cannot believe this is the right/most effective way.
Are there any other ways to tackle this?

Excel VBA: How to use objects defined in a previous module in a new module without defining them again [duplicate]

This question already has answers here:
How to make Excel VBA variables available to multiple macros?
(3 answers)
Closed 5 years ago.
I have previously defined Report_wb in an module Obtain_Data, and now I am writing a new module Module1. I want to use the object Report_wb without defining it again. Is there any way to do that? Thanks!
rather than declaring Report_wb as a dim within a sub, write it as a public declaration at the top of the module
i.e.
'Module 1
Public stringTest as string
Sub SetString()
stringTest = "Hello World!"
End Sub
and then in another module:
'Module 2
Sub TestString()
call SetString
debug.print stringTest
End Sub

How do I pass a range obj variable to a sub in Excel VBA (2016) [duplicate]

This question already has an answer here:
Array argument must be ByRef
(1 answer)
Closed 6 years ago.
Given the following code:
I can not seem to successfully pass a Range Object Variable from one sub-function to another. I spent an entire day researching, and experimenting before I swallowed pride and came here.
Please read the comments below, and reply with any ideas you have regarding why the LAST two lines will not behave.
Public Sub doSomethingToRows(ROI As Range)
*'do Something with the cell values within the supplied range*
End Sub
'
Public Sub testDoAltRows()
Dim RegionOfInterest As Range 'is this an object or not?
'*The following yields: Class doesn't support Automation (Error 430)*
'*Set RegionOfInterest = New Worksheet 'this just gives an error*
Set RegionOfInterest = Worksheets("Sheet1").Range("A1")
RegionOfInterest.Value = 1234.56 '*okay, updates cell A1*
Set RegionOfInterest = Worksheets("Sheet1").Range("B5:D15")
RegionOfInterest.Columns(2).Value = "~~~~~~" '*okay*
'doSomethingToRows (RegionOfInterest) 'why do I get "OBJECT IS REQUIRED" error?
doSomethingToRows (Worksheets("Sheet1").Range("B5:C15")) 'but this executes okay
End Sub
From the msdn documentation of the Call keyword statement,
Remarks
You are not required to use the Call keyword when calling a procedure.
However, if you use the Call keyword to call a procedure that requires
arguments, argumentlist must be enclosed in parentheses. If you omit
the Call keyword, you also must omit the parentheses around
argumentlist. If you use either Call syntax to call any intrinsic or
user-defined function, the function's return value is discarded.
To pass a whole array to a procedure, use the array name followed by
empty parentheses.
From a practical standpoint, even though Subs can be called with or without the "Call" keyword, it makes sense to pick one way and stick with it as part of your coding style. I agree with Comintern - it is my opinion, based on observation of modern VBA code, that using the "Call" keyword should be considered deprecated. Instead, invoke Subs without parenthesis around the argument list.
And now the answer to the important question:
Why does your code throw an error?
Take for example the following Subroutine:
Public Sub ShowSum(arg1 As Long, arg2 As Long)
MsgBox arg1 + arg2
End Sub
We have established that, if not using the Call keyword, Subs must be invoked like so:
ShowSum 45, 37
What happens if it were instead called like ShowSum(45, 37)? Well, you wouldn't even be able to compile as VBA immediately complains "Expected =". This is because the VBA parser sees the parenthesis and decides that this must be a Function call, and it therefore expects you to be handling the return value with an "=" assignment statement.
What about a Sub with only one argument? For example:
Public Sub ShowNum(arg1 As Long)
MsgBox arg1
End Sub
The correct way to call this Sub is ShowNum 45. But what if you typed this into the VBA IDE: ShowNum(45)? As soon as you move the cursor off of the line, you'll notice that VBA adds a space between the Sub name and the opening parenthesis, giving you a crucial clue as to how the line of code is actually being interpreted:
ShowNum (45)
VBA is not treating those parenthesis as if they surrounded the argument list - it is instead treating them as grouping parenthesis. MOST of the time, this wouldn't matter, but it does in the case of Objects which have a default member.
To see the problem this causes, try running the following:
Dim v As Variant
Set v = Range("A1")
Set v = (Range("A1")) '<--- type mismatch here
Notice that you get a "Type Mismatch" on the marked line. Now add those two statements to the watch window and look at the "Type" column:
+-------------+-----+--------------+
| Expression |Value| Type |
+-------------+-----+--------------+
|Range("A1") | |Object/Range |
|(Range("A1"))| |Variant/String|
+-------------+-----+--------------+
When you surround an Object with grouping parenthesis, its default property is evaluated - in the case of the Range object, it is the Value property.
So it's really just a coincidence that VBA allowed you to get away with "putting parenthesis around the argumentlist" - really, VBA just interprets this as grouping parenthesis and evaluates the value accordingly. You can see by trying the same thing on a Sub with multiple parameters that it is invalid in VBA to invoke a Sub with parenthesis around the argument list.
#PaulG
Try this:
Public Sub Main()
Debug.Print TypeName(Range("A1"))
Debug.Print TypeName((Range("A1")))
End Sub
okay, I knew after I posted this question I'd be struck by lighting and receive an answer.
When passing an object VARIABLE to a sub-function and wishing to use parentheses "()", one must use CALL! Thus the correction to my code sample is:
**CALL doSomethingToRows(RegionOfInterest)**
Thank you!
Maybe we're talking about different things, but here's an example to make it a bit clearer what I mean.
Option Explicit
Sub TestDisplay()
Dim r As Range
'Create some range object
Set r = Range("A1")
'Invoke with Call.
Call DisplaySomething(r)
'Invoke without Call.
DisplaySomething r
End Sub
Sub DisplaySomething(ByVal Data As Range)
Debug.Print "Hi my type is " & TypeName(Data)
End Sub
Both calls work perfectly. One with Call and the other without.
Edit:
#Conintern. Thanks for explaining that. I see what is meant now.
However, I still respectively disagree.
If I declare the following:
Function DisplaySomething(ByVal Data As String)
DisplaySomething = "Hi my type is " & TypeName(Data)
End Function
and invoke it:
Debug.print DisplaySomething(Range("A1"))
I believe that Excel has been clever and converted to a string. It can do that by invoking the Default Parameter and can convert to a string.
However, as in the original parameter example, If I declare the following:
Function DisplaySomething(ByVal Data As Range)
DisplaySomething = "Hi my type is " & TypeName(Data)
End Function
There is no call on the Default Parameter, however it is called, because Excel was able to resolve it to that type.
Function DisplaySomething(ByVal Data As Double)
DisplaySomething = "Hi my type is " & TypeName(Data)
End Function
will return a double because it was able to coerce to a double.
Indeed in those examples the Default was called.
But in this example we are defining as Range. No Default called there however it is invoked - brackets or no brackets.
I believe this is more to do with Excel and data coercion.
Similar to the following:
Public Function Test(ByVal i As String) As Integer
Test = i
End Function
and invoking with:
Debug.print Test("1")
BTW, yes I know this isn't an object without a Default parmeter. Im pointing out data coercion. Excel does its best to resolve it.
Could be wrong mind you...

Optional argument in VBA causes error while executing [duplicate]

This question already has answers here:
VBA does not accept my method calling and gives Compile error: Syntax error [duplicate]
(2 answers)
Closed 7 years ago.
I tried to create procedure that passes 2 arguments, mandatory and optional, before I added optional argument procedure was running correctly. Here is Code:
Sub a2(var As String, Optional num As Integer = 5)
MsgBox (num)
End Sub
Sub start_a2()
a2 ("null_text", 5)
End Sub
When I pass any second argument, running procedure start_a2 fails at 1st line: Sub start_a2(), VBA higlight this line with Yellow and returns Syntax error, but do not provide any details. Second argument is inproperely passed?
Does it work if you use Call? Such as
Sub start_a2()
Call a2("null_text", 5)
End Sub
Edit: Though the above will work, #SO's comment below is right on (Thanks!); you can just use
Sub start_a2()
a2 "null_text", 5
End Sub

vb.net subroutine in event handler gives nullobjectreference [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I can't seem to figure out what's going on here:
EDIT: Let's try this... here's an outline of my code...
Class form1
Dim table1 as DataTable
Sub refreshdata()
table1.load() 'this puts data in table1
End Sub
Sub sub1 ()
msgbox(table1.rows.count) 'this returns the number 15
End Sub
Sub combobox_closed (ByVal...) Handles ComboBox1.DropDownClosed
msgbox(table1.rows.count) 'this returns the NullReferenceException
So what's the difference between the last two subs? Why can one access the table and not the other?
In the posted code. table1 is being declared as a local variable in one subroutine, and you are trying to access it from another subroutine. Make it a class scoped private variable instead to be able to access it from both routines.
Private table1 As DataTable = Nothing