我在On Error Resume Next
中使用VBA
太多了。这是一种懒惰的习惯。
如果工作簿尚未从工作簿中删除,则以下将autofit
某些列 - 如果已删除,则会引发错误,编译器将移至下一行代码。
我可以使用哪种其他方法来获得相同的结果?
On Error Resume Next
bkExampleWorkbook.Sheets("Foo").Columns("E:G").AutoFit
bkExampleWorkbook.Sheets("Bar").Columns("K:M").AutoFit
On Error GoTo 0
答案 0 :(得分:4)
假设您正在使用相同的工作表名称,并且只想在它们存在时调整它们的大小,您可以从一个函数开始,以便更容易查看它们是否存在并调整它们的大小:
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