在另一个模块Excel VBA中调用时,公共变量值重置

时间:2015-06-15 13:53:54

标签: excel vba excel-vba reference global

在Excel中,我有两个模块,比如说module1和module2。

在module1中,我声明了一个公共变量:

Public offsetNumber As Integer

在sub中,我为'offsetNumber'变量指定了一个数字。

offsetNumber = 2
Msgbox offsetNumber

这会成功显示数字2。

现在,在module2中,我尝试调用变量offsetNumber。

Msgbox offsetNumber

但是,显示的值为0,而不是2。

如何将变量值从module1转移到module2?

UPDTATE:

我尝试过module1.offsetNumber并检查“require variable declarations”。我还检查过以确保该值没有被覆盖(至少在module1中)。

为了更深入,这就是我的module1目前的结构:

Public offsetNumber as Integer

Sub **********

Dim .... (declare variables)
Activecell.EntireRow.Select
currentRow = ActiveCell.Row
offsetNumber = currentRow - 48
Msgbox offsetNumber (returns correct value)

........... (misc code)

Msgbox offsetNumber (returns correct value)

End Sub

这就是我的module2的结构:

Sub *********

Dim ..... (declare variables)

.............. (misc code)

Msgbox offsetNumber (returns 0)

For rowCounter = 2 to lastRow
    If Sheets("****").Cells(rowCounter, 3) = ****** Then
        Sheets("****").Activate
        Rows(rowCounter + offsetNumber).Select
    End If
Next rowCounter

End Sub

执行module1后的“立即”窗口中,出现以下行

? offsetNumber 

返回值0。

SOLUTION:

这对我有用:

模块1:

Public globalOffsetNumber as Integer

Sub **********

Dim .... (declare variables)
Activecell.EntireRow.Select
currentRow = ActiveCell.Row
offsetNumber = currentRow - 48
globalOffsetNumber = offsetNumber (new line)

Msgbox offsetNumber (returns correct value)

........... (misc code)

Msgbox offsetNumber (returns correct value)

End Sub

单词数:

Sub *********

Dim ..... (declare variables)

.............. (misc code)

Msgbox globalOffsetNumber (now returns correct value)

For rowCounter = 2 to lastRow
    If Sheets("****").Cells(rowCounter, 3) = ****** Then
        Sheets("****").Activate
        Rows(rowCounter + globalOffsetNumber).Select
    End If
Next rowCounter

End Sub

2 个答案:

答案 0 :(得分:1)

You don't have to do anything for a public variable which is declared in one module to be accessible in another. Try this experiment:

In module 1 have:

Option Explicit
Public s As String

Sub setvar()
    s = "Hi"
End Sub

In module 2 have:

Sub readvar()
    Debug.Print s
End Sub

If you first run setvar and then immediately run readvar you should see "Hi" displayed in the immediate window.

My guess is that you are somehow or other resetting the project after running your first sub but before running the second.

答案 1 :(得分:0)

我添加了相同的问题, 不要将“ Public s As String”放在模块2中。 定义会重置变量。