根据条件将单元格值分配给数组

问题描述 投票:1回答:2

这是我第一次在VBA中使用数组。我试图根据某些条件检查我的数组的值。

我通过Locals Window检查我的数组值。窗口是空的。我做错了什么?

Option Explicit

Sub test()

'define dynamic array
Dim sn As Variant 
Dim i As Long

'Loop through all the row
For i = 1 To Rows.Count
    If Cells(i, 12).Value = "Renewal Reminder" And Not IsEmpty(Cells(i, 12).Value) Then
    'assign cell value to array
    sn = Cells(i, 1).Value
    Debug.Print "aaa" ' there are 8 cell values that meet the condition
    End If
Next i

End Sub

更新

Dim sn as Varient以Error突出显示

用户定义的类型未定义

arrays excel vba excel-vba
2个回答
2
投票

除了在错误消息中显示的拼写错误之外,您实际上并没有将sn用作数组 - 您只是将每个值存储在标量变量中,替换之前在该变量中的值。

以下内容对您有用:

Option Explicit

Sub test()

    'define dynamic array
    Dim sn As Variant
    Dim cnt As Long
    Dim i As Long
    ReDim sn(1 To 1)
    cnt = 0
    'Loop through all the row
    For i = 1 To Cells(Rows.Count, "L").End(xlUp).Row
        If Cells(i, 12).Value = "Renewal Reminder" Then
            'assign cell value to array
            cnt = cnt + 1
            ReDim Preserve sn(1 To cnt)
            sn(cnt) = Cells(i, 1).Value
            Debug.Print "aaa" ' there are 8 cell values that meet the condition
        End If
    Next i

    For i = 1 To cnt
        Debug.Print sn(i)
    Next

End Sub

正如the answerChemiadel中所提到的,如果你知道那是什么,最好使用适当的基类型来声明你的变量。

因此,如果您知道列A包含文本,请将Dim sn As Variant替换为

Dim sn() As String

或者,如果是双精度数,请使用

Dim sn() As Double

如果列A可以包含各种不同类型,则使用Variant可能是合适的。

注意:使用()时不必包含Variant,因为Variant变量可以在标量,数组,对象等之间切换。


1
投票

您需要以这种方式声明Array并避免Variant数据类型:

  1. 静态数组:固定大小的数组 dim sn(10) as String
  2. 动态数组:您可以在代码运行时调整数组大小。 dim sn() as String

使用ReDim Preserve扩展阵列,同时保留现有值

ReDim Preserve sn(UBound(sn) + 10) 

检查reference

© www.soinside.com 2019 - 2024. All rights reserved.