You are here:

Excel/passing values to other proceedures


QUESTION: I am finding it difficult to pass the value of a declared variable from on sub to another.  how is this done?  ie
sub Setmode()

Dim Mode as String

Mode = "t"

End Sub

Sub UseSetmode()


End Sub.

ANSWER: You use what is called arguments:

sub Setmode()
   Dim Mode as String
   Mode = "t"
   UseSetmode Mode
End Sub

Sub UseSetmode(Mode As String)
End Sub.

---------- FOLLOW-UP ----------


Thank you for this, however it did not work in the context that I am working in where the value is needed in a sub quite far removed from the original procedure.  How does one declare variables, at the start of the program, that can be accessed/used by any sub at anytime of the program?  Sorry I am new to VBA and programming.

You can declare a variable at the top of a module:

Private msModuleVariable As String

If declared this way (above all subs/functions) then this variable is visible to all subs and functions inside that module. It stays "alive" for as long as your project is loaded in Excel (though certain conditions, such as pressing End do zap the content!)

You can also use (only in a normal module!):

Public gsPublicVariable As String

This variable will be visible to the entire VBA project.

Note that generally speaking using module-level or public variables is frowned upon by professional developers. It makes your code less "portable".
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Jan Karel Pieterse


Excel and Excel/VBA questions


Excel MVP

Self employed Excel developer

Bachelor in Chemical Engineering

Awards and Honors
Microsoft MVP award since 2002

Past/Present Clients
Shell, Fortis bank, ABN-AMRO bank, Morgan Stanley, ...

©2016 All rights reserved.