VBA 中的变量根据其不同的作用域级别,分为公共变量、模块级变量和本地变量 3 种。不同的变量有不同的声明方法。

1、公共变量需在模块的第一个过程前用 Public 语句声明。

示例代码如下:

Option Explicit
Public grade As Integer
Sub test()
    Range("B2") = "公共变量"
End Sub

 

2、模块级变量需在模块的第一个过程前用 Dim 或 Private 语句声明。

示例代码如下:

Option Explicit
Dim str As String Private grade As Integer Sub test() Range("B3") = "模块级变量" End Sub

 

3、本地变量在过程中用 DIm 或 Static 语句声明即可。

示例代码如下:

Option Explicit
Sub test()
Dim str As String
Static grade As Integer
    Range("B4") = "本地变量"
End Sub

相关文章:

  • 2021-07-15
  • 2021-11-05
  • 2022-03-04
  • 2021-11-29
  • 2021-04-27
  • 2021-11-06
  • 2021-09-29
猜你喜欢
  • 2021-12-26
  • 2022-03-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
相关资源
相似解决方案