【问题标题】:Assigning cell value to an array based on a condition根据条件将单元格值分配给数组
【发布时间】:2017-12-29 02:37:12
【问题描述】:

这是我第一次在 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 以错误突出显示

用户定义类型未定义

【问题讨论】:

  • 没有看到您的电子表格我不能肯定地说,但这里有一些想法。这是使用基于 1 或 0 的索引吗? (A1 列是“第 1 行第 1 列”还是“第 0 行第 0 列”?)您是否在 sn 或 Debug 行上设置了断点?一旦函数完成所需的几毫秒时间结束,监视窗口是否仍保持该值?
  • 您没有使用 sn 作为数组 - 您只是将单个单元格的值存储到变量中。 (FWIW,您的And Not IsEmpty(Cells(i, 12).Value) 毫无意义,因为如果Cells(i, 12).Value = "Renewal Reminder"True,那么您已经知道该单元格不是Empty。)
  • @YowE3K 啊哈,你是对的。
  • 您的编辑说您有一行写着Dim sn as Varient,但这并没有出现在您发布的代码中。如果错误是正确的,你有一个错字。
  • @YowE3K 天哪,谢谢我把Variant 拼错了Varient

标签: arrays vba excel


【解决方案1】:

除了错误消息中显示的拼写错误之外,您实际上并没有将 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

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

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

Dim sn() As String

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

Dim sn() As Double

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

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

【讨论】:

【解决方案2】:

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

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

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

    dim sn() as String
    

使用 ReDim Preserve 扩展数组,同时保留现有值

ReDim Preserve sn(UBound(sn) + 10) 

查看reference

【讨论】:

  • 您也可以使用Dim sn As Variantsn定义为Variant,然后在其中放置一个数组。
  • 但我不确定我的数组的大小,因为它完全取决于条件。那样的话ReDim Preserve sn(UBound(sn) + 10) 只加了10个,如果超过10个呢?
  • 使用 ReDim 并首先指定数组的类型避免 Variant 数据类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多