If "iserror" 具有不同对象类型的 FOR 循环

If "iserror" FOR loop with varying object type

我有一列包含字符串类型(例如 "N/A")或数字。我正在尝试编写一个 vba 代码,如果 FOR 循环遇到字符串类型,它将被转换为 0。本质上发生的事情是代码沿着一列 (K) 的值(例如。 $10, $600, $5200, N/A, $5), 并保留单元格值,如果它是一个数字,如果单元格中有文本,那么文本将转换为 0。范围是 (K6:K10),公式看起来像,

=If(iserror(K6/10) = TRUE, 0, K6)

代码:

Dim a As Integer
Dim DilutedRev As Integer
For a = 6 To 10
    DilutedRev = ActiveCell(a, 11).Value
    If IsError(DilutedRev / 100) = True Then
        ActiveCell(a, 11) = 0
    Else
        ActiveCell(i, 11) = DilutedRev
    End If

首先正如你在上一个问题中指出的那样; Activecell 仅指 activecell 它是一个单元格而不是范围。你想要 Cells().

接下来通过在循环内重新声明变量,它允许 Excel 每次确定其类型。如果不是,它将是 excel 第一次分配的类型,并且您不能将文本值存储为整数类型。

然后我们测试该变量是否为数字。

但是你可以跳过它并按照@Jeeped 的建议去做。

Dim a As Integer

For a = 6 To 10
    Dim DilutedRev 
    DilutedRev = Cells(a, 11).Value
    If Not isnumeric(DilutedRev) Then
        Cells(a, 11) = 0
    Else
        Cells(a, 11) = DilutedRev
    End If

使用 IsNumeric function 确定单元格是否包含数字。

Dim a As Long

With ActiveSheet
    For a = 6 To 10
        If IsNumeric(.Cells(a, "K").Value2) Then
            .Cells(a, 11) = CLng(.Cells(a, "K").Value2)
        Else
            .Cells(a, 11) = 0
        End If
    Next a
End With

使用 ActiveCell property like you did was not 'best practise' due to the relative origin point¹; better to use the Range.Cells property.

VBA 函数 return 布尔值(例如 IsNumeric, IsError 等)不必与 True 或 False 进行比较。它们已经不是 True 就是 False。

我用过Range.Value2 property to check but the Range.Value property也可以用

通常值得明确定义 Range.Parent worksheet property rather then relying implicitly on the ActiveSheet property


¹ 严格来说,偏移ActiveCell as you did but the result is completely relative to the current selection on the worksheet and is generally not considered 'best practise'. With D5 selected on the worksheet, activecell(1,1) references D5 and activecell(2,3) references F6. In a very special circumstance, this behavior may be desirable but generally speaking it is better to use the Range.Cells property and use the row_number and column_number to reference the cell from the Worksheet Object视角并没有错,不是作为ActiveCell的偏移位置。