2

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.