在公共函数中声明变量(Excel VBA)

时间:2018-06-07 11:17:16

标签: excel vba excel-vba

我有一些在另一个函数中按顺序调用的公共函数......像这样:

Public Sub func1()
  Operation 1
End Sub

Public Sub func2()
  Operation 2
End Sub

Public Sub func3()
  Operation 3
End Sub

Sub Execute()
  Call func1()
  Call func2()
  Call func3()
End Sub

我想要理解的是,如果我在每个函数中都声明了一个公共变量,就像这样:

Dim LastRow as Long
LastRow = Sheets("Project_Name").Cells(Rows.count, "B").End(xlUp).row

可以安全地假设我可以在func1()中声明一次并在func2()func3()中使用它吗?

或者我必须在每个函数中声明它3倍?

由于

1 个答案:

答案 0 :(得分:4)

这是一个全局变量,您可以在func1中进行分配(尽管我会更改这些名称,因为它们是潜艇)。请注意,公共变量在subs之外的模块顶部声明。我已将一个子的名称更改为my_Execute,因为Execute让我想起了几种编程语言中的关键词。

Option Explicit
Public a As Long

Public Sub func1()
    a = 1
End Sub

Public Sub func2()
    MsgBox a
End Sub

Public Sub func3()
    MsgBox a    
End Sub

Public Sub my_Execute()
    func1
    func2
    func3
End Sub

在本地声明一次并按值传递all作为参数(ByVal)。注意:这里它在my_Execute中声明为本地,然后作为参数传递给其他子节点。

Option Explicit

Public Sub func1(ByVal a As Long)
   MsgBox "func1 " & a
End Sub

Public Sub func2(ByVal a As Long)
    MsgBox "func2 " & a
End Sub

Public Sub func3(ByVal a As Long)
    MsgBox "func3 " & a
End Sub

Public Sub my_Execute()
    Dim a As Long
    a = 1
    func1 a
    func2 a
    func3 a
End Sub

传递ByRef因此可以改变a路线:

Option Explicit
Public Sub func1(ByRef a As Long)
   a = a + 1
End Sub

Public Sub func2(ByRef a As Long)
    a = a + 2
End Sub

Public Sub func3(ByRef a As Long)
     a = a + 3
End Sub

Public Sub my_Execute()
    Dim a As Long
    a = 1
    func1 a
    func2 a
    func3 a
    MsgBox a
End Sub

有关ByRef和ByVal的信息MSDN