2015-06-05 123 views
2

我有以下(以前工作)的代碼,將公式轉換爲它們的常量值。我將它附加到電子表格上的表單按鈕上。它工作正常,然後決定休息。我點擊按鈕或運行宏,一個盒子出現「自動化錯誤」。 Excel幫助將其描述爲「自動化錯誤(錯誤440)」。
我遵循論壇的建議,在各個地方插入「On Error Resume Next」語句。我已經嘗試重新創建宏。我嘗試了一些不同版本的宏。但還沒有設法解決它。我如何擺脫這個錯誤?它是否類似於Java和Python中的try catch語句?VBA - 自動化錯誤 - Excel 2013

Sub RangeOfFormulasToConstants() 
' 
' Changes a selection of Formulas into their values thus removing the formula. 
' 
' Keyboard Shortcut: Ctrl+q 

Dim Rng As Range 
Dim WorkRng As Range 
On Error Resume Next 
xTitleId = "Useful box" 
Set WorkRng = Application.Selection 
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8) 
Application.ScreenUpdating = False 
For Each Rng In WorkRng 
    Rng.Value = Rng.Text 
Next 
Application.ScreenUpdating = True 

End Sub 

我有其他的宏,目前與電子表格和表單按鈕工作。詳細如下。

Sub CopyFormulasNonCalculate() 

' 
' PasteMacro Macro 
' 
' Keyboard Shortcut: Ctrl+m 
' 
    On Error Resume Next 
    Set Ret = Application.InputBox(Prompt:="Please select a range where you want to paste", Type:=8) 
    On Error GoTo 0 
    If Not Ret Is Nothing Then 
     Selection.Copy 

     Range("C2:F2").Copy Destination:=Ret 



      Application.CutCopyMode = False 
    End If 
End Sub 

Sub CopyFormulasCalculate() 
Dim Ret As Range 
Dim RangeToCopy As Range 

Set RangeToCopy = Range("H3:AF3") 
' 
' PasteMacro Macro 
' 
' Keyboard Shortcut: Ctrl+m 
' 
    Set Ret = Application.InputBox(Prompt:="Please select a range where you want to paste", Type:=8) 
    If Not Ret Is Nothing Then 
     RangeToCopy.Copy Destination:=Ret 
     Ret.Resize(1, RangeToCopy.Columns.Count).Calculate 

      Application.CutCopyMode = False 
    End If 
End Sub 
+0

什麼行有錯誤? – 99moorem

+0

Sub RangeOfFormulasToConstants() – AMorton1989

+0

這根本沒什麼意義。 – AMorton1989

回答

1

不應該在使用Rng.Value = Rng.Text而不知道你在抄錄回單元格。這會嘗試將顯示的單元格值設置爲格式,並將其作爲值返回給單元格。從本質上講,你得到的是單元看起來不一定是價值的東西。

改爲使用Rng = Rng.ValueRng = Rng.Value2。這需要公式已經返回的基礎值並將單元格的值設置爲該值。

Sub RangeOfFormulasToConstants() 
    ' Changes a selection of Formulas into their values thus removing the formula. 
    ' Keyboard Shortcut: Ctrl+q 

    Dim WorkRng As Range, xTitleId As String 

    Application.ScreenUpdating = False 
    xTitleId = "Useful box" 

    On Error GoTo bm_Exit 
    Set WorkRng = Application.InputBox("Range: ", xTitleId, Selection.Address, Type:=8) 
    WorkRng = WorkRng.Value 'do it all at once - no need to loop through 

bm_Exit: 
    Application.ScreenUpdating = True 
End Sub 

不是通過對每個代碼不當行錯誤絆相反,該捕獲錯誤和混洗代碼執行關閉的bm_Exit書籤將環境退出之前恢復。

+0

我重新啓動,修改了代碼,它工作正常。謝謝一堆。 – AMorton1989