2017-09-14 219 views
0

這將是一個問題,指定的區域應該轉換爲值除#REF!是錯誤的。VBA - 值轉換#REF!例外

Sub keplet_helyett_ertek() 
    Range("C3:J65").Select 

    For Each akt_range In Selection.Areas 
    If akt_range.Value <> CVErr(xlErrRef) Then 
     akt_range.Formula = akt_range.Value 
    End If 
    Next 
End Sub 

然後,運行時間 '13' 錯誤

enter image description here

+1

'Selection.Areas'列舉區域。區域的「價值」是一個二維數組。顯然你想'Selection.Cells'。然後再次,[你不需要'選擇'](https://stackoverflow.com/q/10714251/11683)。 – GSerg

回答

0
For Each akt_range In Selection.Areas 

應該是

For Each akt_range In Selection 

爲了更高效的替代

Range("C3:J65").Select 
For Each akt_range In Selection.Areas 

Dim akt_range As Range 
For Each akt_range In Range("C3:J65") 
0
Sub keplet_helyett_ertek() 
Dim akt_range As Range, ok As Boolean 
    Range("C3:J65").Select 
    For Each akt_range In Selection 
    ok = Not IsError(akt_range.Value) 
    If Not ok Then ok = (akt_range.Value <> CVErr(xlErrRef)) 
    If ok Then akt_range.Formula = akt_range.Value 
Next 
End Sub 
+1

我認爲'ok'不會增加代碼的可讀性或功能,應該刪除。 「IsError」顯然是一個布爾函數,並且設置標誌的唯一原因是在原始評估之外需要標誌條件。我建議將@ jkpieterse的答案和你的並排比較,看看哪一個更易讀。 – 2017-09-14 07:55:15

2

的另一個問題是,如果一個小區DOS不包含錯誤值你得到的類型不匹配了。參加測試的是:

For Each akt_range In Range("C3:J65") 
    If Not IsError(akt_Range.Value) Then 
     akt_range.Formula = akt_range.Value 
    End If 
    Next 
0

如果像該問題時,你只在排除#REF!錯誤,是正確的校驗感興趣:

For Each akt_range In Range("C3:J65") 
    If CStr(akt_range.Value2) <> CStr(CVErr(xlErrRef)) Then 
     akt_range.Value = akt_range.Value2 
    End If 
    Next 

技術上,上述將在返回#REF!的錯誤代碼字符串的公式的特殊情況下失敗,例如="Error 2023"。該絕對防彈檢查是這樣的:

For Each akt_range In Range("C3:J65") 
    If Not IsError(akt_range.Value2) Or CStr(akt_range.Value2) <> CStr(CVErr(xlErrRef)) Then 
     akt_range.Value = akt_range.Value2 
    End If 
    Next 

如果要排除所有錯誤,一個更好的解決辦法是使用.SpecialCells()循環之前,以消除該範圍的錯誤:

For Each akt_range In Range("C3:J65").SpecialCells(xlCellTypeFormulas, xlLogical + xlNumbers + xlTextValues) 
    akt_range.Value = akt_range.Value2 
    Next