Use Variable in multiple subs VBA - excel

So I'm using excel 2010, and right now, I'm trying to use calculate the value of a variable in one sub, and want it to be used in multiple subs, except I can't figure out how to do this. Here is an example of what I'm using in its most basic form
Public Sub Calc()
Dim i As Integer
i = 10 - 5
End Sub
'Other sub that will use the value for i calculated in the Calc sub
Sub Macro()
y = i +5
End Sub
How am I suppose to be able to use/pass this value for "i" in/into the sub macro?

Move the Dim above the subs:
Public i As Integer
Public Sub Calc()
i = 10 - 5
End Sub
Sub Macro()
y = i + 5
MsgBox y
End Sub
Sub MAIN()
Call Calc
Call Macro
End Sub
Try running MAIN()

Insert new module and define i as:
Public i As Integer
Then you'll be able to use it whenever you want.
For further information, please see: Scope of variables in Visual Basic for Applications

I would like to use Function instead of Sub.
Sub Main()
Msgbox Macro(calc)
end Sub
Function Calc() as Integer
Dim i As Integer
i = 10 - 5
Calc = i
End Function
Function Macro(i as Integer) as Integer
Macro = i + 5
End Function

Related

How to make counting the cells with button in Excel, VBA?

I'm making the simple app using the VBA code and forms in Excel. So, I need to have a simple Private Sub CommandButton1_Click() method which will call for calculation methods and write down the results in Label. How can I do this? (yes, I'm new to VBA)
Private Sub CommandButton1_Click()
MsgBox "My text here"
End Sub
Private Sub UserForm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
CommandButton1_Click
End Sub
But instead of the calling the window with my text there I need to make calculations of cells.
Will it be correct if I'll write code like shown down there and somehow add the calculations of cells?
Sub Button1_Click()
Sheet1.testing
End Sub
Sub testing()
Dim ell As Object
Dim post As String
Dim Count As Double
Dim cm As String
End Sub
In vba editor, double-click on the command-button in the UserForm to enter the code:
If you put the sub-procedure in the module (e.g doSomething sub-procedure), you have to add the module name:
Call Module1.doSomething
Option Explicit
Private Sub CommandButton1_Click()
Call doSomething
End Sub
'--------------------------------------
Sub doSomething()
MsgBox "My text here"
End Sub
#FunThomas helped me (you can see it in comments to this question). And here is the solution on my question:
Private Sub CommandButton1_Click()
testing
End Sub
Sub testing()
Dim value1
calc = value1 + 10
Label1 = value1 + 10
Dim ell As Object
Dim post As String
Dim Count As Double
Dim cm As String
Dim sText As String
sText = Sheet1.Range("A1").Value
Label2 = sText
End Sub

Get variable from nested macro into "outer" macro by calling/running other workbook/file

I have a main macro (macro1) running smaller macros (macroA and macroB) in other *.xlam or *.xslm files .
I need, besides the little macros (A+B) doing their job, specific variables and their values in the "outer" macro (macro1) for further use in its code.
Is there a way of passing variable values from within the macros A+B to macro1?
Background:
I know that declaring a Public Variable can be used in different macros. I also know how to pass variables or their values from one macro to a following one. But (given my example below) how can I give a variable "back" to macro1?
Example (1) of passing variables in between Subs without calling other workbooks/files (working):
Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
Set wbA = Workbooks.Open("C:\file.xlsx")
Set wbB = Workbooks.Open("C:\file2.xlsx")
OtherSubRoutine
End Sub
Sub OtherSubRoutine()
Debug.Print wbA.Name
End Sub
OUTPUT: file.xlsx
Example (2) of passing variables from called Sub to another from other workbook/file (non-working):
Public count As Integer
Sub macro1()
Run file.xlam! & macroB, argument1, argument2
Debug.Print count 'second print
End Sub
Sub macroB(argument1, argument2)
'code that does something
count = 5
Debug.Print count 'first print
End Sub
OUTPUT first print: 5
OUTPUT second print: 0
Code finishes without errors or debug messages. Where is my mistake?
You should transform the Sub in a function (able to return something) and call it in a little different way:
Put the next function in workbook 1 (for exemplification, I used 'PERSONAL.XLSB'):
Function GiveMeFive(x As Long, y As Long) As Long
Debug.Print x + y 'not important, ONLY TO SEE IT WORKING IN immediate Window
GiveMeFive = 5
End Function
Call it from another workbook in this way:
Sub testFunctionWithArgsOtherWb()
Dim x As Long
x = Run("PERSONAL.XLSB!" & "GiveMeFive", 4, 3)
Debug.Print x
End Sub
It will return in Immediate Window: 7 (from the function itself) and 5, what the function returned when it was called...
Second version:
If you don't like functions, you can return a Public variable value using a Sub, in this way:
Create a Public variable in another workbook (also used Personal.xlsb), but in ThisWorkbook code module:
Public MyVar As Long
Create such a Sub in a standard module:
Sub MyMacro(x As Long, y As Long)
ThisWorkbook.MyVar = x * y
End Sub
Call the Sub from a different workbook and read the global variable, modified by the called Sub:
Sub testValFromOtherWB()
Dim x As Long
Run "PERSONAL.XLSB!" & "MyMacro", 4, 3
x = Workbooks("PERSONAL.XLSB").MyVar
Debug.Print x
End Sub
Please, test them and send some feedback.

VBA Form to Only Calculate once 3 textboxes are filled

Currently I have a VBA form with 4 textboxes, the first starts populated with a value, the remaining 3 will start blank. My goal is to have the formula run only when all 3 are greater than zero or "", and recalculate on subsequent changes, provided again that all 3 have values. I found a slightly similar thread for this but it was on Java, not VBA. This is what I have so far. I've tried IF functions and it still throws an error. Thank you!
Option Explicit
Public RTempFormP As Double
Private Sub UserForm_Initialize()
RTempFormP = Range("RPress1")
TextBox1 = RTempFormP
End Sub
Private Sub TextBox2_AfterUpdate()
Call RunTemp
End Sub
Private Sub TextBox3_AfterUpdate()
Call RunTemp
End Sub
Private Sub TextBox4_AfterUpdate()
Call RunTemp
End Sub
Sub RunTemp()
Dim CoeffA As Double: CoeffA = TextBox2
Dim CoeffB As Double: CoeffB = TextBox3
Dim CoeffC As Double: CoeffC = TextBox4
Dim RTempFormT As Double
RTempFormT = CoeffB / (CoeffA - Log10(RTempFormP * 14.5)) - CoeffC
Label7 = (9 / 5) * (RTempFormT - 273.15) + 32
End Sub

Excel VBA editor auto-UNcapitalizing properties

Usually the Excel VBA editor auto-capitalizes keywords and property names for you, but now it is un-capitalizing them. Like this:
Private Sub CommandButton1_Click()
Range("A1").Value = "test"
End Sub
changes to:
Private Sub CommandButton1_Click()
Range("A1").value = "test"
End Sub
And then the code doesn't run properly. Any ideas what could cause this behavior? Thanks.
Possible reasons
You have named one of the modules as value
You have a variable called value in one of your procedures/functions
You have a procedure/function with that name
Example for point 1
Example for point 2
Sub Sample()
Range("A1").value = "Sid"
End Sub
Sub Blah()
Dim value As Long
value = 1
End Sub
Example for point 3
Sub Sample()
Range("A1").value = "Sid"
End Sub
Sub value()
'
'
'
End Sub

Challenge: MS Excel VBA Programming for the Absolute Beginner

I'm learning VBA using a combination of VBA For Dummies and the above mentioned book. The latter, presents a simple challenge (Challenge 2, Chapter 2) that I'd like to ask some for some feedback about.
The challenge is as follows:
Place a Command Button control on a worksheet and write a program in the Click()
event procedure that increments a variable by 5 with every click of the mouse.
Output the value of this variable in a message box.
I've put together the following the code snippet in response:
Sub CommandButton1_Click()
Dim AddClick As Integer
AddClick = Range("A1").Value
AddClick = AddClick + 5
Range("A1").Value = AddClick
MsgBox AddClick
End Sub
Although the code works, I'm pretty sure there's a way to eliminate the use of 'Range("A1").Value' to base the 'AddClick' variable on. How would I go about doing this?
*Update: Thanks to Cody Gray's suggestion (http://articles.techrepublic.com.com/5100-10878_11-5854605.html), I've revised the code to the following - which now works just fine (edited for further simplication):*
Sub CommandButton1_Click()
Static AddClick As Integer
AddClick = AddClick + 5
MsgBox AddClick
End Sub
Simples. Thanks again Cody.
Both previous samples are wrong I think. The correct version is below:
Sub CommandButton1_Click()
Static AddClick As Integer
AddClick = AddClick + 5
MsgBox AddClick
End Sub
Define the variable at module level.
Doing this will increase the scope of the variable from procedure to the module.
Replace the existing code with this one.
Option Explicit
Dim AddClick As Integer
Sub CommandButton1_Click()
AddClick = 0
AddClick = AddClick + 5
MsgBox (AddClick)
End Sub
Note: Defining the variable at procedure level will limit its life.
i.e. the variable won't be accessible outside the scope of the procedure.

Resources