VBA无法处理输入#Value的字段

时间:2014-12-27 03:21:40

标签: excel vba excel-vba

对于每个进入#Value的字段,每个循环都会被触发。我有一个解决方法,因为我不断获得Ge0eral,我需要将其保留到位,但现在我无法通过输入#Value的字段。

下面是一个示例表和代码。

我希望它打印#Value或忽略#Value一起的字段。

Sub TableMessup()
    Dim myTable As Range
    Set myTable = Range("A1:D3")

    Dim mycell As Range
    Dim tempstr As String

    For Each mycell In myTable
        tempstr = Format(mycell.Value, mycell.NumberFormat)

        If tempstr = "Ge0eral" Then
            Debug.Print mycell.Value
        Else
            Debug.Print Format(mycell.Value, mycell.NumberFormat)

        End If
    Next mycell


End Sub  
+---+---+---------+--------+
| a | b |    c    |   d    |
+---+---+---------+--------+
| 1 | 4 | 5       | 50.00% |
| 2 | t | #VALUE! | 20.00% |
+---+---+---------+--------+

2 个答案:

答案 0 :(得分:3)

使用 Mycell.Text 代替 Mycell.Value ,而不是使用 Format()创建字符串。

答案 1 :(得分:2)

您无法打印错误值,因为它不是字符串,而是error类型。

您可以使用单元格的.Text属性。

或者,您可以使用一些条件逻辑,例如:

For Each mycell In myTable
    If IsError(myCell.Value) Then
        Debug.Print "Error at " & myCell.Address
    Else
        tempstr = Format(mycell.Value, mycell.NumberFormat)

        If tempstr = "Ge0eral" Then
            Debug.Print mycell.Value
        Else
            Debug.Print Format(mycell.Value, mycell.NumberFormat)
        End IF
    End If
Next mycell