2017-09-14 39 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