首页 > 解决方案 > 在动态创建的数组中定位单个值

问题描述

我正在尝试创建一个动态数组。我需要使用动态数组的原因是因为我不知道一开始数组中需要多少变量。

数组存在后,我想解析数组中的范围,有时只为其中一个范围隔离一个单元格值。不幸的是,我收到了 Object Required 错误。

我已经在此站点和其他站点上进行了检查,但找不到解释。也许人们对这些行为的称呼有所不同。

Sub get_val()

'get the number of rows
Dim id As Worksheet
Set id = ThisWorkbook.Sheets("ID Sheet")
rc = id.Range("B:B").Find(What:="*", After:=id.Range("B1"), LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row

'Find which ones have "yes" in column Q and create an array
Dim memcache As Variant
Dim x As Integer
x = 1
ReDim memcache(x)
For i = 3 To rc
    If id.Cells(i, 17).Value = "Yes" Then
        ReDim Preserve memcache(x)
        memcache(x) = id.Range("A" & i & ":M" & i)
        x = x + 1
    End If
Next i

' 这就是我遇到问题的地方。'如果我想将其中一个范围复制到工作表上的另一个范围,那效果很好

id.Range("A50:M50").Value = memcache(2) 'this works

'但是,如果我只想在该范围内定位一个单元格的值,它将'不起作用。这会产生“需要对象”错误。

Debug.Print memcache(2).Cells(1, 2).Value 

'为了比较,创建单个范围将起作用

Dim cellrange As Variant

Set cellrange = id.Range("A9:M19")


Debug.Print cellrange.Cells(1, 2).Value ' this will work


End Sub

我希望能够获取保存在数组中的每个范围内的单元格 (1,2) 的值,如果它们符合某个条件,我将使用保存的完整范围更新工作表上的另一个范围大批。

标签: excelvba

解决方案


数组和范围在 VBA 中是不同的东西。数组只是一个值数组,而范围是对工作表上一组单元格的引用。在这种情况下,Memcache是一个数组,但您试图将其视为一个范围。Memcache没有任何单元格,它只有值。

你想要的是替换Debug.Print memcache(2).Cells(1, 2).ValueDebug.Print memcache(2).

如果您显式设置变量类型,则差异会更加明显,例如:

Dim memcache() As String '(or integer, or whatever type of data you're putting into it)
Dim cellrange As Range

推荐阅读