Search code examples
excelvbapublic

How to make the variable public in VBA?


I needed to find the vendornumber value to construct a matrix from the given data. I wrote the code (in VBA) below

(it has more rows for the matrix construction but i cut them here)

Public Sub tryout()
 Dim vendornumber As Integer
 Dim rownumber As Integer
 rownumber = Worksheets("DISTANCE").Range("A2", 
 Worksheets("DISTANCE").Range("A2").End(xlDown)).Rows.Count
    Dim y As Integer
    Do Until (y = rownumber)
       y = vendornumber * (vendornumber + 1)
       vendornumber = vendornumber + 1
    Loop
End Sub

The code works perfectly but I want to use this value in other modules as well. I tried to make the variable public as:

Public vendornumber As Integer

It gave the error:

Invalid attribute in Sub or Function.

Then, I put this row to out of the sub and it gave the error: Overflow and pointed the part of the code below as the reason:

y = vendornumber * (vendornumber + 1)


Solution

  • You need to declare the variables outside.

    Public vendornumber As Integer
    
    Public Sub tryout()
       vendornumber = 1