请参阅表格使用代号

With Worksheets(Sheet1) '* Error here 'my code here End With 

我的工作表的CodeName是Sheet1。
这里的错误说types不匹配。

有人可以帮我删除错误?

1)参考索引表:

 With Worksheets(1) '<stuff here> End With 

“索引”取决于“工作簿中的工作表顺序”。 如果您打印订单,这可能不再涉及同一张表!

2)按名称参考表:

 With Worksheets("Your Sheet Name") '<stuff here> End With 

这是工作表的.Name属性,是在Excel工作表选项卡和VBA项目浏览器的括号中可见的名称。

3)参考表格CodeName:

你build议你实际上想使用工作表的.CodeName属性。 这不能像上面两个例子那样在括号内引用,但是与上面的一些答案相反! 它在创build时被自动分配到一张纸上,并且是“Sheet”,然后是之前创build的CodeNames中的下一个未使用的号码。

使用CodeName的优点是不依赖于图纸顺序(与Index不同),并且只要用户通过在Excel中重命名图纸来更改Name ,它也不会改变。

缺点是代码可能更复杂或模糊。 由于CodeName是只读的[1],这不能改善,但是确保了上述优点! 请参阅参考文档了解更多详情。

第一种使用方式 :直接…

 With Sheet1 '<stuff here> End With 

第二种使用方式 :间接地,可以提供更多的清晰度或灵活性,显示如何使用工作表的CodeName属性…

通过循环读取表单并读取CodeName属性,可以首先find所需表单的IndexName属性。 然后你可以使用这个参考表单。

 Dim sh as WorkSheet Dim shName as String Dim shIndex as Integer ' Cycle through all sheets until sheet with desired CodeName is found For Each sh in ThisWorkbook.WorkSheets ' Say the codename you're interested in is Sheet1 If sh.CodeName = "Sheet1" Then ' If you didn't want to refer to this sheet later, ' you could do all necessary operations here, and never use shName ' or the later With block ' If you do want to refer to this sheet later, ' you will need to store either the Name or Index (below shows both) ' Store sheet's Name shName = sh.Name ' Store sheet's Index shIndex = sh.Index Exit For End If Next sh ' Check if match was found, do stuff as before if it was! If shName = "" Then MsgBox "Could not find matching codename" Else ' Equally to the next line, could use Worksheets(shIndex) With Worksheets(shName) '<stuff here> End With End If 

[1] https://msdn.microsoft.com/en-us/library/office/ff837552.aspx

您可以直接在您的代码中使用工作表代码,就像它们是已声明的variables一样:

 Sub UsingSheetCodeName() With Sheet1 .[a1] = Sheet1.Name End With End Sub 

要在您的代码中使用Worksheet.Index

 With Worksheets(1) ' << this is the index for Sheet1 .Range("A1").Value = "Test" ' modify the value in cell A1 End With 

也许这个代码有助于理解不同的名称和索引

 Sub DisplaySheetnames() Dim wks As Worksheet For Each wks In Worksheets Debug.Print "Index", wks.Index, "of sheet with name: " & wks.Name, "and", "codename " & wks.CodeName Next End Sub 

Sheet1之前和之后使用双引号

 With Worksheets("Sheet1") '* Error here 'my code here End With