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

时间:2017-12-29 02:37:13

标签: arrays excel vba excel-vba

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

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

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突出显示错误

  

未定义的用户定义类型

2 个答案:

答案 0 :(得分:2)

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

以下内容对您有用:

sn

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

因此,如果您知道列A包含文本,请将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 替换为

Dim sn As Variant

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

Dim sn() As String

等。如果列A可以包含各种不同类型,则使用Dim sn() As Double 可能是合适的。

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

答案 1 :(得分:1)

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

  1. 静态数组:固定大小的数组

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

    dim sn() as String
    
  3. 使用ReDim Preserve扩展阵列,同时保留现有值

    ReDim Preserve sn(UBound(sn) + 10) 
    

    检查reference

相关问题