excel - 如何在 vba 中使用 Redim Preserve
问题描述
Sub C()
Dim V
For K = 7 To C_Count
If 0 < Cells(9, K) And Cells(9, K) < 100 Then
lngV = lngV + 1
ReDim Preserve V(lngV)
V(lngV) = Cells(9, K)
End If
Next
End Sub
我只想在 Cells(9,k) 大于 0 且小于 100 时才向数组添加一个值,但该代码会出现错误。有人可以帮我解决这个问题吗?
解决方案
使用ReDim Preserve
- 您需要使用括号声明变量才能“应用”第一个变量
ReDim Preserve
:Dim V() As Variant
- 请注意,这可以写得更有效,即通过创建对行范围的引用并将其列数用于
ReDim
数组。最后,只需要一个或一个都不ReDim Preserve
需要。
Option Explicit
Sub WriteToZeroBasedArray()
Dim V() As Variant ' Note the parentheses!
Dim Index As Long
Dim cCount As Long: cCount = 10 ' e.g.
Dim c As Long
For c = 7 To cCount
If 0 < Cells(9, c).Value And Cells(9, c).Value < 100 Then
ReDim Preserve V(Index)
' A safer way (Option Base related):
'ReDim Preserve V(0 To Index)
V(Index) = Cells(9, c).Value
Index = Index + 1
End If
Next c
If Index = 0 Then Exit Sub
Debug.Print Join(V, vbLf)
End Sub
Sub WriteToOneBasedArray()
Dim V() As Variant ' Note the parentheses!
Dim Index As Long
Dim cCount As Long: cCount = 10 ' e.g.
Dim c As Long
For c = 7 To cCount
If 0 < Cells(9, c).Value And Cells(9, c).Value < 100 Then
Index = Index + 1
ReDim Preserve V(1 To Index)
V(Index) = Cells(9, c).Value
End If
Next c
If Index = 0 Then Exit Sub
Debug.Print Join(V, vbLf)
End Sub
推荐阅读
- testing - TestCafe EC2 网络日志
- python - 将两个数据框绘制成一个条形图,区分它们的值
- javascript - (已解决)React/JS 如何获取 props.data 的最后一个索引的值,它是一个对象
- css - 如何连续运行两个关键帧的CSS动画
- html - Div 元素未正确显示
- python - 查找作为 LSP 参数的模块定义(pyright)
- c# - C# 在使用时删除缓存
- python-3.x - 使用 Python OpenCV 和 GStreamer 从 UDP 接收器读取 RTSP 流
- python - 为什么有时 selenium 可以定位对象,有时却没有?
- java - 在 Java 中读取大量日志文件并发布到 API 端点的最有效方法是什么?