简体   繁体   中英

Excel VBA - check if active worksheet is first worksheet

I need to check if the active worksheet is the first worksheet in the workbook. This code isn't working at all, but I'm hoping I was on the right track.

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

This is simple

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

You can't compare reference types with = and <> - you have to use 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

Here you go:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM