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