arrays - 将 2 个范围组合成一个数组并过滤
问题描述
我有 2 个范围,都具有相同的行数,不同的列数(可能会有所不同)。
范围 1:
A, 1, 1, 1
B, 2, 4, 8
C, 3, 9, 27
D, 4, 16, 64
范围 2:
1, 1
16, 64
81,
256, 1024
我想将这些值导入 Excel 中的多数组,但前提是范围 2 的第 n 列(在本例中为第 2 列)不是空值。那么我最终会得到一个如下所示的数组:
输出 1:
A, 1, 1, 1, 1, 1
B, 2, 4, 8, 16, 32
D, 4, 16, 64, 256, 1024
到目前为止 - 我已经开始了一个功能:
Function Report(rng1 As Range, rng2 As Range)
Dim matrix() As Double
Dim all_rng As Range
all_rng = Union(rng1, rng2)
End Function
解决方案
这是可能的决定。
注释:
1.为了测试方便,我把Function
to改为了Sub
,因为我不能一步一步完成函数
2.有几行用于测试目的(在注释中标记)
3.我假设要填充的列数正确inrng2
在它的第一行
4。有带有.Select
语句的注释行 - 取消注释它,按 F8 逐步进行,您将看到它是如何工作的。
答案。
这是代码:
Sub Report() 'rng1 As Range, rng2 As Range)
Dim matrix() As Variant ' use variant if you have a mix of letters and numbers
Dim x As Long, y As Long
Dim r As Long, c As Long
Dim rows() As Long, i As Long, rowCnt As Long
' used for test purposes
Dim rng1 As Range, rng2 As Range
Set rng1 = Range(Cells(1, 1), Cells(4, 4))
Set rng2 = Range(Cells(1, 9), Cells(4, 10))
' find out columns count per each range's row 1
x = Range(rng1.Cells(1, 1), rng1.Cells(1, rng1.Columns.Count)).Columns.Count
' I assume that the correct number of columns in rng2 is in the first row
' you may change the row number if needed
y = Range(rng2.Cells(1, 1), rng2.Cells(1, rng2.Columns.Count)).Columns.Count
' check that all rows have all columns filled
For i = 0 To rng1.rows.Count - 1
' if all columns in rng2 are filled then add number of the row to an array of row numbers
If Not rng2.Cells(i + 1, y) = " " Then ' fix evaluation condition if needed - that is what was copied from post
ReDim Preserve rows(rowCnt)
rows(rowCnt) = i + 1
rowCnt = rowCnt + 1
End If
Next
i = UBound(rows) - 1
' set dimension of an matrix array
ReDim matrix(rows(i), x + y)
' start filling the matrix
' go through matrix by row
For r = LBound(rows) To UBound(rows)
' fill each row column by column
'gothrough first range - it has x columns in it
For c = 0 To x - 1
' rng1.Cells(rows(r), c + 1).Select
matrix(r, c) = rng1.Cells(rows(r), c + 1).Value
Next
' then without changing matrix's row
' go through second range - it has y columns
For c = 0 To y - 1
' rng2.Cells(rows(r), c + 1).Select
matrix(r, c + rows(UBound(rows))) = rng2.Cells(rows(r), c + 1).Value
Next
Next
' print the matrix to the sheet (optional - delete when convert this back to Function)
For r = LBound(matrix) To UBound(matrix)
For c = 0 To x + y - 1
Cells(10 + r, c + 1) = matrix(r, c)
Next
Next
End Sub
如果您有任何问题 - 将它们放在评论中。
推荐阅读
- javascript - 如何在 React 中过滤传入的道具?
- python - 将用户输入数据保存在 kivy 中并存储以供以后使用/分析 python
- javascript - 制作一个 js 小书签,在新窗口中打开网站并使其全屏显示(mac ver)
- html - 如果嵌入另一个标签,Chrome 和 Edge 是否会停止计算容器的预期行为?
- javascript - Node和npm在执行JS文件时抛出错误?
- amazon-web-services - 如何将数组作为环境变量放入 boto3 Lambda 函数
- python - 为本地工作 git 存储库创建一个 requirements.txt,而不用 .py 代码对导入进行 grepping
- javascript - 将类添加到按钮后,我的单击功能不适用于按钮
- java - 为什么我的 Thymeleaf 视图 HTML 文件不显示 Spting 应用程序中的对象列表?
- javascript - ThemeProvider:“主题”道具是必需的。→ React.js