1
我有一個充滿ActiveX控件的工作表。我知道他們是在工作表上的錯誤,所以這是我已經實現的功能來重置控件並保持其行爲。VBA錯誤處理程序在引用ActiveX控件時出現「For Each __ in __」失敗:運行時錯誤438
問題是錯誤處理程序沒有捕獲由於試圖訪問列表框的自動大小屬性而發生的運行時錯誤438(列表框沒有自動大小屬性,因此運行時間438錯誤)。
Public Sub RefreshCtrlSheet(Optional ByRef HiddenElements As Variant)
'This sub refreshes ActiveX Objects on the Ctrl Sheet
Dim objX As Object 'Holds OLEObjects from Control Sheet
Dim tempWidth As Double 'Store size of object to restore
Dim tempHeight As Double 'after resetting
Dim tempLeft As Double
Dim tempTop As Double
Dim i As Integer
With Sheet1
'Error Handler
On Error GoTo NotTheObjsUrLooking4
For Each objX In .OLEObjects
'If Name has Button in it
If InStr(objX.Name, "Button") > 0 Then
'Implement different button sizes
If objX.Name = "LoadDataButton" Then
tempHeight = 24.75
tempWidth = 24.75
Else
tempHeight = 30
tempWidth = 80
End If
Else
tempHeight = objX.Height
tempWidth = objX.Width
End If
'Check to see if elements should be hidden
If Not IsMissing(HiddenElements) Then
For i = 1 To UBound(HiddenElements)
If InStr(objX.Name, HiddenElements(i)) Then
objX.Visible = False
End If
Next i
End If
tempLeft = objX.Left
tempTop = objX.Top
'Autosize to refresh shingking controls (ActiveX Bug)
objX.object.AutoSize = True '----------------------RUNTIME ERROR HERE!
objX.object.AutoSize = False
objX.Width = tempWidth
objX.Height = tempHeight
objX.Left = tempLeft
objX.Top = tempTop
NotTheObjsUrLooking4: '----------------------------THIS WORKS EVERY OTHER ERROR
Next objX
On Error GoTo 0
End With
End Sub
當我添加一個新的ActiveX列表框時,它開始出現問題,這很奇怪,因爲我已經有另一個,它從來沒有問題。
感謝任何人都可以提供的幫助!
編輯:
感謝墊的,就是這樣。
新代碼與:
...
'Error Handler
On Error GoTo CleanFail
...
'Other code
...
NotTheObjsUrLooking4:
Next objX
End With
On Error GoTo 0
Exit Sub
CleanFail:
Err.Clear
Resume NotTheObjsUrLooking4
End Sub
爲什麼你不需要「On Error GoTo 0」?我總是儘管你需要重置Error行爲,或者錯誤處理程序中的Resume是否爲你做了這些事情? –
@BryanHarper你只需要'GoTo 0'來「重置錯誤處理」(通常在設置On Error Resume Next後) - On Error GoTo跳轉總是程序本地的,所以在完全處理一個運行時錯誤; 'Resume'關鍵字重置錯誤狀態(證明:嘗試調用'Resume'而不處於錯誤狀態;-) –