8

VBA 中引用 WorkSheet 的新方法

 3 years ago
source link: https://zhiqiang.org/coding/refer-excel-worksheet-in-vba.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

VBA 中引用 WorkSheet 的新方法

作者: 张志强

, 发表于 2009-12-14

, 共 426 字 , 共阅读 318 次

最近学到一招,效果不错~

在写 VBA 中常需要引用某个 WorkSheet 对象,一般通过工作表名

Dim ws As Worksheet 
Set ws = ThisWorkbook.Worksheets("Sheet2Name")

或者索引号

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(2)

来引用。但这样做有一个不好的地方,就是如果工作表改名或者工作簿有删除、插入动作,以上引用可能会失效。但使用 Code Name 在上面两种情况下都会一直有效(在 VBA 里一张工作表对象显示为 Sheet2(Sheet2Name), Code Name 即为"Sheet2」,可通过属性窗口修改为有意义的字串):

Dim ws As Worksheet
Set ws = Sheet2

而且在写法上也更简单。

但有一个缺点,跨工作表时这种方法就无效了。

Q. E. D.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK