检查特定工作表是否为活动工作表

时间:2011-09-22 12:41:28

标签: excel excel-vba vba

如何检查特定纸张是否为活动纸张?

我希望将特定功能用于名称为数据的工作表。

我可以使用以下代码检查数据表是否存在

Dim ws As Worksheet
Set ws = Wb.Sheets("Data")
If ws Is Nothing Then

Else

但是如何检查数据表是否是活动表? 有没有像

这样的东西
If ws Is Activesheet Then

更新

我在addin的Class模块中添加了以下代码。

我要做的是从此插件管理其他Excel工作表。如果活动工作表的名称为“数据”,我想调用程序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

3 个答案:

答案 0 :(得分:4)

您还可以检查对象(我们永远不知道用户是否已打开工作簿,其中工作表具有相同的名称):

Sub test()
  On Error Resume Next
  If ActiveWorkbook.Worksheets("Data") Is ActiveSheet Then MsgBox ("ok")
  On Error GoTo 0
End Sub

请参阅MSDN

感谢brettdj提供有关错误处理的提醒。

[编辑]在您的代码中:

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

答案 1 :(得分:2)

你应该

  1. 使用错误处理,因为工作表可能不存在
  2. 对于插件,您通常会使用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
    

答案 2 :(得分:1)

我会用:

If Wb.ActiveSheet.Name = ws.Name Then

End If