vba - 获取打开的工作簿的工作表名称

标签 vba excel

我有下面的代码,提示用户选择工作簿,我想确保用户正在选择特定文件,为此我想在打开工作簿时验证工作表名称是否与我期望的匹配他们是:

    Private Sub CommandButton1_Click()

        Dim wb1 As Workbook, wb2 As Workbook
        Dim Ret1
        Set wb1 = ActiveWorkbook

        Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
        , "Please a file to load from")
        If Ret1 = False Then Exit Sub

        Set wb2 = Workbooks.Open(Ret1)

    If wb2.Sheet1.Name = "Sum" And wb2.Sheet2.Name = "Names" And wb2.Sheet3.Name = "Things" Then
    MsgBox "Fine"
'Code Here
    Else
    MsgBox "Issue"
'Code Here
    End If

        wb2.Close SaveChanges:=False

        Set wb2 = Nothing
        Set wb1 = Nothing

    End Sub

不幸的是,当我运行上面的代码时,我得到一个“对象不支持这个属性或方法错误”。上线If wb2.Sheet1.Name = "Sum" And wb2.Sheet2.Name = "Names" And wb2.Sheet3.Name = "Things"
请帮忙!

最佳答案

您可以使用此功能检查工作表是否存在:

Function IsSheetExist(wb As Workbook, shName As String) As Boolean
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = wb.Worksheets(shName)
    On Error GoTo 0
    IsSheetExist = Not ws Is Nothing
End Function

并像这样使用它:
If IsSheetExist(wb2, "Sum") And IsSheetExist(wb2, "Names") And IsSheetExist(wb2, "Things") Then
    MsgBox "Fine"
    'Code Here
Else
    MsgBox "Issue"
    'Code Here
End If

如果要检查工作簿中是否按特定顺序存在工作表,可以使用以下方法:
Function IsContainsSheetsInOrder(wb As Workbook) As Boolean
    IsContainsSheetsInOrder = False

    If wb.Sheets.Count < 3 Then Exit Function
    If wb.Sheets(1).Name <> "Sum" Then Exit Function
    If wb.Sheets(2).Name <> "Names" Then Exit Function
    If wb.Sheets(3).Name <> "Things" Then Exit Function

    IsContainsSheetsInOrder = True
End Function

接着:
If IsContainsSheetsInOrder(wb2) Then
    MsgBox "Fine"
    'Code Here
Else
    MsgBox "Issue"
    'Code Here
End If

关于vba - 获取打开的工作簿的工作表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22872935/

相关文章:

vba - 引用新添加的工作表

c# - 帮助将通用 List<T> 转换为 Excel 电子表格

excel - 功能化事件驱动的无模式用户窗体类

excel - 错误读取表字段所需的属性

python - 如何从 Python 运行 Excel VBA/宏

java - 当新的 Excel 工作表添加到文件夹中时自动更新数据库

vba - 如何使用 VBA 在文本文件中的句子(用破折号)下划线

excel - 输入框中的浏览按钮查找文件 Excel2007 Vba

excel - 如何分别识别分组列和隐藏列?

excel - VBA查找列中出现的最大单词及其计数