获取已打开工作簿的工作表名称

时间:2014-04-04 21:01:17

标签: excel vba excel-vba

我有下面的代码,用户被要求选择一个工作簿,我想确保用户正在选择一个特定的文件,为了做到这一点,我想在打开工作簿时验证工作表名称是否匹配什么我期待他们:

    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"

请帮忙!

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

或者,更接近原始脚本,将wb1.sheet#.Name更改为wb1.sheets(#).Name,如下所示:

    If wb2.Sheets(1).Name = "Sum" And wb2.Sheets(2).Name = "Names" And wb2.Sheets(3).Name = "Things" Then