如何在两个Excel对象中共享变量?

时间:2019-01-29 09:27:18

标签: excel vba

如何使用从ThisWorkbook到Sheet1的变量?

打开Excel文件后,我想存储Lastrow值。此Lastrow值将稍后在命令按钮中使用。我在命令按钮中使用msgbox来查看该值是否为share,而msgbox却不显示任何内容。

这是来自Excel对象ThisWorkbook

Public Lastrow As Long

Sub Workbook_Open()
    With ActiveSheet
        Lastrow = Range("A" & .Rows.Count).End(xlUp).Row
        Application.Goto Reference:=.Range("A" & Lastrow + 1)

        MsgBox "Last row is" & Lastrow
        .Range("A" & Lastrow + 1).Select
    End With
End Sub

这是来自Excel对象Sheet1

Sub CommandButton2_Click()
    Dim wb As Workbook
    MsgBox "Last row is" & wb.Lastrow
End Sub

我想将值从工作簿带到sheet1。例如,一旦打开Excel文件,msgbox将显示6,commandbutton2中的msgbox将显示相同的内容。

1 个答案:

答案 0 :(得分:0)

这里的问题是,在...

Dim wb As Workbook
MsgBox "Last row is" & wb.Lastrow

... wbNothing因为你没有设置一个工作簿(它应该抛出一个错误)。因此,要么设置一个工作簿:

Dim wb As Workbook
Set wb = ThisWorkbook
MsgBox "Last row is" & wb.Lastrow

…或只使用ThisWorkbook.Lastrow

我建议激活Option Explicit:在VBA编辑器中,转到工具选项 Require Variable Declaration


或者将Public LastRow As Long移到模块。这样,您可以像MsgBox "Last row is" & Lastrow一样在任何地方使用它。