VBE 中的工作表名称

Worksheet names in VBE

我注意到我的工作簿对 VBE 中的每个组件都有两个不同的名称。 name1 和 name2 有什么区别? 我应该参考哪一个,这样我才能确定我的宏能正常工作?

Control 是 sheet 的代码名称,而 Plan 1 是 sheet 的选项卡名称。后者可以很容易地由用户更改,因此如果可以的话,使用代号更安全 - 例如,参考:

control.range("A1:A10")

而不是:

sheets("Plan 1").Range("A1:A10")

请注意,除了包含代码的工作簿之外,您不能使用 sheet 代号来引用工作簿中的 sheet,除非您设置对该工作簿的项目的引用,或使用 a function that loops through each sheet in the other workbook testing the codename property of each.

"Plan1" 是选项卡名称,它显示在工作表底部的选项卡上。

"Control" 是代号,可以在 VBA 中使用它来直接引用特定的工作表对象。

Sheets("Plan1").Cells(1, 1).ValueControl.Cells(1, 1).Value 将产生相同的输出。

VBE 中的每个文档类型 vbComponent 都有一个 Name 和一个 CodeName:

  • Name 是在 Excel UI.
  • 中的 sheet 选项卡上可见的名称
  • CodeName 是 sheet 对象在你的 VBA.
  • 中可以引用的名称

示例:

Sub Names()

  Debug.Print Control.Name              'Prints "Plan 1"
  Debug.Print Control.CodeName          'Prints "Control"

  'This approach uses the sheet name in a call to `Sheets`,
  ' which will break if a user changes the name of the sheet
  'The sheets collection returns an object, so you don't get
  ' Intellisense, or compile-time error checking
  Debug.Print Sheets("Plan 1").Name     'Prints "Plan 1"
  Debug.Print Sheets("Plan 1").CodeName 'Prints "Control"

End Sub