【问题标题】:VBA:: Passing range results into an arrayVBA:: 将范围结果传递到数组中
【发布时间】:2011-06-23 09:12:02
【问题描述】:

我目前正在研究 VBA 中的搜索功能,该功能将从搜索范围中获取结果并将单元格位置的地址输入到数组中。

我尝试使用以下代码设置数组。

Dim FindRange1 as Range
Dim Find1 as Range
Dim Results1() as Variant
Dim R1 as integer
Dim Max as integer

Max = Range("E7:E1000").Cells.Count

       Set FindRange1 = Worksheets("Properties").Range("P7:P1000")
            If ILsearch.P1B1.Value = True Then
                For R1 = 1 To Max
                    For Each Find1 In FindRange1
                        If (Find1.Value < TextBox1) And (Find1.Value > "0") Then
                            Results1(R1) = Find1.Address
                        End If
                    Next Find1
                Next R1
            End If

【问题讨论】:

  • 那么问题是什么?它在做什么你不希望它做什么?

标签: arrays vba excel for-loop


【解决方案1】:

您需要对数组进行标注;

redim Results1(Max) '//this will leave an empty Results1(0)

最好使用 0 索引;

redim Results1(Max-1) 
...
Results1(R1 - 1) = Find1.Address

请注意,这是创建一个带有“空白”的数组,其中只有满足您条件的索引才会被填充。

【讨论】:

  • 最好明确指定下限:ReDim Results1(1 To Max)ReDim Results1(0 To Max-1)。顺便说一句,我不明白为什么后者会比前者更好或更差——除了后者不可避免地会导致你经历几个调试周期,因为你忘了写 - 1 几个地方!呸,+1。
  • 是的,我已将我的代码设置为选项基数 1,所以我觉得“代码”ReDim Results1(1 To Max)“代码”更适合我的代码。谢谢!
猜你喜欢
  • 2014-03-06
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
相关资源
最近更新 更多