excel - 在动态创建的数组中定位单个值
问题描述
我正在尝试创建一个动态数组。我需要使用动态数组的原因是因为我不知道一开始数组中需要多少变量。
数组存在后,我想解析数组中的范围,有时只为其中一个范围隔离一个单元格值。不幸的是,我收到了 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) 的值,如果它们符合某个条件,我将使用保存的完整范围更新工作表上的另一个范围大批。
解决方案
数组和范围在 VBA 中是不同的东西。数组只是一个值数组,而范围是对工作表上一组单元格的引用。在这种情况下,Memcache
是一个数组,但您试图将其视为一个范围。Memcache
没有任何单元格,它只有值。
你想要的是替换Debug.Print memcache(2).Cells(1, 2).Value
为Debug.Print memcache(2)
.
如果您显式设置变量类型,则差异会更加明显,例如:
Dim memcache() As String '(or integer, or whatever type of data you're putting into it)
Dim cellrange As Range
推荐阅读
- c++ - 使用相同的着色器但没有相同的纹理或颜色绘制多个 VAO 的最佳方法是什么
- django - 如何在 ModelBackEnd 中检查 Django 中的非活动用户
- php - 如何将此json转换为数组。我想将我的视图的数据 [x] 显示为表格
- clang-format - 如何使用 clang-format 在 Kdevelop 中设置代码格式?
- next.js - 为什么不应用 JSX CSS?
- node.js - 节点模块是针对节点模块 v 72 编译的。需要 v 64
- splunk - 如何将文本行分成多个事件
- python-3.x - log1pexp 在 Tensorflow 中不可用?
- c# - C#。如果“等待之后”线程很忙,会发生什么?
- c++ - 使用 OIIO 时架构 x86_64 的未定义符号