Excel VBA – 检查活动工作表是否是第一个工作表

我需要检查活动工作表是否是工作簿中的第一个工作表。 这个代码根本不工作,但是我希望我在正确的轨道上。

Sub CheckFirstSheet() If Sheets(1) = ActiveSheet Then MsgBox "This is the first worksheet." If Sheets(1) <> ActiveSheet Then MsgBox "This is not the first worksheet." End Sub 

这很简单

 Sub test() If ActiveSheet.Index = 1 Then MsgBox "This is the first worksheet." If ActiveSheet.Index <> 1 Then MsgBox "This is not the first worksheet." End Sub 

干得好:

 Sub CheckFirstSheet() If ActiveSheet.Index = 1 Then MsgBox "This is the first worksheet." Else MsgBox "This is not the first worksheet." End If End Sub 

你不能比较引用types与=<> – 你必须使用Is

 Sub CheckFirstSheet() If Sheets(1) Is ActiveSheet Then MsgBox "This is the first worksheet." Else MsgBox "This is not the first worksheet." End If End Sub