2011-09-22 82 views
2

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

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

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

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

Else 

但是,如何判断是否数据表是有源片或不? 是有像

UPDATE任何事情:

我已经加入以下在插件的类模块的一个代码。

我想要做的是管理这个插件的其他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 

回答

1

你应该

  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 
    
+0

所以如果没有'数据'它会抛出一个错误?我试过但'On Error GoTo 0'没有执行 –

+0

它不会抛出一个错误。它将执行IF测试的第一个“Is Nothing”分支。更新的MsgBox代码将使这个更清晰 – brettdj

+0

@Sangram:看看如何在VBA中处理错误>> http://www.cpearson.com/excel/errorhandling.htm – JMax

1

我会用:

If Wb.ActiveSheet.Name = ws.Name Then 

End If 
+0

我写在Excel插件的代码,这就是为什么我将无法使用ThisWorkbook.ActiveSheet。对? –

+0

以上解决方案whats wb? –

+0

就是你在给出的那段代码中使用的'Wb',我认为它是活动工作簿 – Jandrejc

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 
相关问题