【问题标题】:Getting vector of values from loop in VBA从VBA中的循环中获取值向量
【发布时间】:2016-10-21 09:55:55
【问题描述】:

我有一列可能有 N/As。我正在运行一个循环来检查是否存在 N/A 错误并弹出带有错误位置的 MsgBox。 我遇到的问题是从有错误的相应列中存储一个值。

Option Explicit

Dim i As Integer
Dim where As Variant
Dim numbers(1 To 20) As Variant

For Each i In Range("b2:b" & lastrow)
If IsError(i) = True Then
where = Range("B" & i.Row).Address
MsgBox "Missing data was found in " & where
numbers (i) = Range("D" & i.Row).Value
End If
Next i

此代码有问题,如获取不匹配错误(运行时错误“13”)。 请指出我在这里做错的正确方向。 谢谢

编辑:我只引用了部分代码,这就是为什么没有 Sub/End Sub

【问题讨论】:

  • 如果lastrow 从未获得任何值,则它保持为空并且Range("b2:b" & lastrow) 将出错
  • 它的 last_non_empty_row
  • 我建议...我只是想确保它设置在任何地方(因为它也没有声明)
  • 如果lastrow 设置正确但已超过 21 岁,那么您将收到此错误...当错误弹出时,您能分辨哪一行突出显示吗?
  • 事实上,您的代码似乎无法运行,因为您将 i 声明为 Integer 但在 For Each 中使用它,该变量需要 Object 类型的变量(或Variant).

标签: excel vba


【解决方案1】:
Private Const lastrow As Integer = 10

Sub GetErrors()
    Dim oneCell As Range
    Dim where As Variant
    Dim numbers As Variant

    where = vbCrLf
    For Each oneCell In Range("b2:b" & lastrow).Cells
        If IsError(oneCell.Value) = True Then
            where = where & Range("B" & oneCell.Row).Address & vbCrLf
            If (Not IsArray(numbers)) Then
                ReDim numbers(0)
            Else
                ReDim Preserve numbers(UBound(numbers) + 1)
            End If
            numbers(UBound(numbers)) = Range("D" & oneCell.Row).Value
        End If
    Next oneCell

    MsgBox "Error was found in : " & where
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多