检查一个特定的工作表是否是activesheet
如何检查特定工作表是否为活动工作表?
我想要具有名称数据的工作表使用特定的function。
我可以使用下面的代码检查数据表是否存在
Dim ws As Worksheet Set ws = Wb.Sheets("Data") If ws Is Nothing Then Else
但是如何检查数据表是否是活动表? 有什么事吗?
If ws Is Activesheet Then
更新:
我在addin的Class模块中添加了以下代码。
我想要做的是从这个插件pipe理其他Excel表。 如果活动工作表名称为“Data”,我想调用过程paste_cells
。
Public WithEvents App As Application Private Sub App_WorkbookActivate(ByVal Wb As Workbook) MsgBox "Activate" Dim ws As Worksheet Set ws = Wb.Sheets("Data") If ws Is ActiveSheet Then ' if active sheet is having name Data App.OnKey "^v", Procedure:="Paste_cell" 'paste cell is procedure i want to add when active sheet is Data Else App.OnKey "^v" End If End Sub
你应该
- 使用error handling作为工作表可能不存在
-
对于一个插件,你通常会使用ActiveWorkbook,即
Dim ws As Worksheet On Error Resume Next Set ws = ActiveWorkbook.Sheets("Data") On Error GoTo 0 If ws Is Nothing Then MsgBox "Data sheet not found" Else If ws.Name = ActiveWorkbook.ActiveSheet.Name Then MsgBox "Data sheet found and is active" Else MsgBox "Data sheet found but is inactive" End If End If
您也可以检查对象(我们永远不知道用户是否已经打开了工作簿,其中工作表具有相同的名称):
Sub test() On Error Resume Next If ActiveWorkbook.Worksheets("Data") Is ActiveSheet Then MsgBox ("ok") On Error GoTo 0 End Sub
请参阅MSDN
感谢brettdj关于error handling的提醒。
[编辑]在你的代码中:
Public WithEvents App As Application Private Sub App_WorkbookActivate(ByVal Wb As Workbook) MsgBox "Activate" Dim ws As Worksheet On Error Resume Next Set ws = Wb.Sheets("Data") On Error GoTo 0 If Not ws Is Nothing and ws Is ActiveSheet Then ' if active sheet is having name Data App.OnKey "^v", Procedure:="Paste_cell" 'paste cell is procedure i want to add when active sheet is Data Else App.OnKey "^v" End If End Sub
我会用:
If Wb.ActiveSheet.Name = ws.Name Then End If