在 VBA 中检查哪个 Excel 工作表处于活动状态(当前显示)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5174088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:11:27  来源:igfitidea点击:

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

vbaexcel-vbaexcel

提问by omer bach

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.

我正在寻找一种检查 Excel 工作表当前是否处于活动状态(当前显示)的方法。我对同步方法感兴趣,而不是对事件感兴趣。

回答by Patrick Honorez

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)

您可以使用set sh = ActiveSheet, 或strShName = ActiveSheet.Name
要测试工作表 Xyz 是否处于活动状态:If ActiveSheet.Name = "xyz" Then
您还可以使用If ActiveSheet.CodeName = "Sheet1" Then(VBE 名称)

回答by ChrisB

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