omer bach
omer bach

Reputation: 2405

In VBA check which excel sheet is active (currently shown)

I'm looking for a method of checking if an excel sheet is currently active (currently shown). I'm interested in a synchronous method and not in an event.

Upvotes: 13

Views: 91666

Answers (3)

Mohamed Elmoslmany
Mohamed Elmoslmany

Reputation: 11

If Sheet1 Is ActiveSheet Then

Call

ElseIf Sheet2 Is ActiveSheet Then

Upvotes: 0

ChrisB
ChrisB

Reputation: 3225

Test for matching worksheet and workbook names.

Function IsActiveSheet(ByVal targetSheet As Worksheet) As Boolean
    IsActiveSheet = targetSheet.Name = ActiveSheet.Name And _
            targetSheet.Parent.Name = ActiveWorkbook.Name
End Function

It's a function. Place it in a module, and then call it from another procedure like this:

Sub Test()
    Dim mySheetVar As Worksheet
    Set mySheetVar = ActiveWorkbook.Worksheets("Sheet1")

    ' Here's the function call which returns TRUE or FALSE.
    MsgBox IsActiveSheet(mySheetVar)
End Sub

Upvotes: 2

iDevlop
iDevlop

Reputation: 25272

You could use set sh = ActiveSheet, or strShName = ActiveSheet.Name.
To test if sheet Xyz is active: If ActiveSheet.Name = "xyz" Then
You can also use If ActiveSheet.CodeName = "Sheet1" Then (VBE name)

Upvotes: 30

Related Questions