How do I declare a global variable in VBA?

前端 未结 8 1170

I wrote the following code:

Function find_results_idle()

    Public iRaw As Integer
    Public iColumn As Integer
    iRaw = 1
    iColumn = 1
8条回答
  •  遥遥无期
    2020-11-22 09:24

    The question is really about scope, as the other guy put it.

    In short, consider this "module":

    Public Var1 As variant     'Var1 can be used in all
                               'modules, class modules and userforms of 
                               'thisworkbook and will preserve any values
                               'assigned to it until either the workbook
                               'is closed or the project is reset.
    
    Dim Var2 As Variant        'Var2 and Var3 can be used anywhere on the
    Private Var3 As Variant    ''current module and will preserve any values
                               ''they're assigned until either the workbook
                               ''is closed or the project is reset.
    
    Sub MySub()                'Var4 can only be used within the procedure MySub
        Dim Var4 as Variant    ''and will only store values until the procedure 
    End Sub                    ''ends.
    
    Sub MyOtherSub()           'You can even declare another Var4 within a
        Dim Var4 as Variant    ''different procedure without generating an
    End Sub                    ''error (only possible confusion). 
    

    You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.

    Two other quick things:

    1. Be organized when using workbook level variables, so your code doesn't get confusing. Prefer Functions (with proper data types) or passing arguments ByRef.
    2. If you want a variable to preserve its value between calls, you can use the Static statement.

提交回复
热议问题