use*_*007 7 excel vba worksheet excel-vba
我在此代码中遇到"类型不匹配"错误:
With Worksheets(Sheet1) '* Error here
'my code here
End With
Run Code Online (Sandbox Code Playgroud)
我的表CodeName
是'sheet1'
.
有人可以帮我删除错误吗?
Wol*_*fie 21
1)参见表格索引:
With Worksheets(1)
'<stuff here>
End With
Run Code Online (Sandbox Code Playgroud)
"索引"取决于"工作簿中的工作表顺序".如果你随机播放你的纸张订单,这可能不再涉及同一张纸了!
2)参见表格名称:
With Worksheets("Your Sheet Name")
'<stuff here>
End With
Run Code Online (Sandbox Code Playgroud)
这是.Name
工作表的属性,在Excel工作表选项卡和VBA项目浏览器的括号中可见.
3)按CodeName参考表格:
您建议您实际上想要使用.CodeName
工作表的属性.这不能像上面两个例子那样在括号内引用,但确实存在与上面的一些答案相反的情况!它在创建时自动分配给工作表,并且是"工作表",然后是先前创建的代码名称中的下一个未使用的编号.
使用的优点CodeName
是它不依赖于工作表顺序(Index
与之不同),如果用户Name
仅通过在Excel中重命名工作表来更改它,则不会更改.
缺点是代码可能更复杂或模棱两可.由于CodeName
是只读[1],这无法改进,但确实具有上述优点!有关详细信息,请参阅参考文档.
使用它的第一种方式:直接...
With Sheet1
'<stuff here>
End With
Run Code Online (Sandbox Code Playgroud)
使用它的第二种方式:间接地,可以提供更多的清晰度或灵活性,显示如何使用CodeName
工作表的属性......
通过循环覆盖并读取CodeName
属性,您可以首先找到所需工作表的属性Index
或Name
属性.然后你可以使用它来引用表格.
Dim sh as WorkSheet
Dim shName as String
Dim shIndex as Long
' 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
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
Run Code Online (Sandbox Code Playgroud)
[1] https://msdn.microsoft.com/en-us/library/office/ff837552.aspx
您可以直接在工作表代码中使用工作表代码名,就好像它们被声明为变量一样:
Sub UsingSheetCodeName()
With Sheet1
.[a1] = Sheet1.Name
End With
End Sub
Run Code Online (Sandbox Code Playgroud)