假设您正在使用相同的工作表名称并且只想在它们存在时调整它们的大小,您可以从一个函数开始,以便轻松查看它们是否存在并在它们存在时调整它们的大小:
基础知识
Function AutoFitSheetRange(objWorkBook As Workbook, _
strSheetName As String, _
strSheetRange As String) As Boolean
Dim sheet As Worksheet, boolSheetFound As Boolean
For Each sheet In objWorkBook.Worksheets
If sheet.Name Like strSheetName Then
boolSheetFound = True
Exit For
End If
Next
If boolSheetFound Then
objWorkBook.Sheets(strSheetName).Range(strSheetRange).AutoFit
AutoFitSheetRange= True
Else
AutoFitSheetRange= False
End If
End Function
使用它
然后,您可以以适合您调整特定范围大小的任何方式遍历您的工作表(并将其简写为列):
AutoFitSheetRange bkExampleWorkbook, "Foo", "E:G"
AutoFitSheetRange bkExampleWorkbook, "Bar", "K:M"
不要忘记添加错误处理
您不想摆脱错误处理,但您希望该函数确保您仍然处理错误,但比 On Error Resume Next 更优雅,这可能会导致不良结果:
'Error Handled version
Function AutoFitSheetRange(objWorkBook As Workbook, _
strSheetName As String, _
strSheetRange As String) As Boolean
On Error Goto AutoFitSheetRangeError
Dim sheet As Worksheet, boolSheetFound As Boolean
For Each sheet In objWorkBook.Worksheets
If sheet.Name Like strSheetName Then
boolSheetFound = True
Exit For
End If
Next
If boolSheetFound Then 'Resize the range!
objWorkBook.Sheets(strSheetName).Range(strSheetRange).AutoFit
AutoFitSheetRange = True
Else
AutoFitSheetRange = False
End If
Exit Function ' No error hit so exit
AutoFitSheetRangeError:
AutoFitSheetRange = False
Debug.Print Err.Message 'Print out the debug error
End Function
灵活的错误响应!
这使您可以灵活地查看列是否已调整大小,而不管是否发生错误,从而使未来的决策更容易:
If AutoFitSheetRange(bkExampleWorkbook, "Foo", "E:G") Then
MsgBox "I couldn't resize Foo! Doing nothing."
End If
If AutoFitSheetRange(bkExampleWorkbook, "Bar", "K:M") Then
'Do something here
End If
我没有机会亲自测试这个,但让我知道它是怎么回事。
编辑:
根据@brettdj 的评论,我认为最好将检查工作表存在的功能分开以使其更加简洁。如果您只想检查工作表是否存在,那么这个功能就足够了:
'Error Handled version
Function SheetExists(objWorkBook As Workbook, strSheetName As String) As Boolean
On Error Goto SheetExistsError
Dim sheet As Worksheet
For Each sheet In objWorkBook.Worksheets
If sheet.Name Like strSheetName Then
SheetExists = True
Exit Function
End If
Next
SheetExistsError:
SheetExists = False
Debug.Print "Couldn't find sheet " & Err.Description 'Print out the debug error
End Function