获取打开的工作簿的工作表名称
我有下面的代码,其中用户被要求select一个工作簿,我想确保用户select一个特定的文件,并做到这一点,我想validation打开工作簿时,表名匹配我所期待的他们是:
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"
请帮助!
或者,更贴近他原来的脚本,将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
您可以使用此function检查图纸是否存在:
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