gpt4 book ai didi

excel - 仅将二维数组的某些元素/列写回工作表

转载 作者:行者123 更新时间:2023-12-04 22:21:58 27 4
gpt4 key购买 nike

我有一个动态二维数组,它的数据比我需要的多,我只想将数组的某些元素(列)写回工作表。这可能吗?例如:

Sub writeArray()
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim arSource() As Variant
Dim a As Long
Dim b As Long

Set wsDest = wbPT.Worksheets("Import")
Set wsSource = wbSource.Worksheets("Export")

wsDest.Activate

ReDim Preserve arSource(3 To wsSource.Range("B" & Rows.Count).End(xlUp).row, 2 To 40) '

For a = LBound(arSource, 1) To UBound(arSource, 1)
For b = LBound(arSource, 2) To UBound(arSource, 2)
arSource(a, b) = wsSource.Cells(a, b)
Next b
Next a
End Sub

该数组在第一维中包含 3 到 271 个元素,在第二维中包含 2 到 40 个元素。

在 39 个元素(列)中,我只想要这些列:4、5、6、7、8、23、35 和 36。

在与列相关的目标工作表上:2、3、4、5、6、7、13 和 14。我需要源数组中的第 4 列现在移动到目标工作表上的第 2 列和第 5 列源位于目标工作表的第 3 列,依此类推,共 8 列。我不需要任何其他数据。 - 我应该尝试另一种方式吗?

最佳答案

我将使用源工作表和目标工作表中的列号创建两个数组,然后您可以将循环减少到仅 1,从而找到源工作表列中的单元格数,然后将该范围复制到目标工作表。

Sub TestWriteArray()

Dim inputColumns As Variant
inputColumns = Array(4, 5, 6, 7, 8, 23, 35, 36)

Dim outputColumns As Variant
outputColumns = Array(2, 3, 4, 5, 6, 7, 13, 14)

writeArray inputColumns, outputColumns
End Sub



Sub writeArray(ByVal ipSourceColumns As Variant, ByVal ipDestColumns As Variant)

If UBound(ipSourceColumns) <> UBound(ipDestColumns) Then

Err.Raise _
17, _
"Columns Mismatch", _
"The number of columns in the source and desination arrays do not match"

End If

Dim wsSource As Worksheet
Set wsSource = ActiveWorkbook.Worksheets("Sheet1")

Dim wsDest As Worksheet
Set wsDest = ActiveWorkbook.Worksheets("Sheet2")


Dim myIndex As Long
For myIndex = LBound(ipSourceColumns) To UBound(ipSourceColumns)

Dim myLastRow As Long
myLastRow = wsSource.Cells(Rows.Count, ipSourceColumns(myIndex)).End(xlUp).Row
wsSource.Range(wsSource.Cells(3, ipSourceColumns(myIndex)), wsSource.Cells(myLastRow, ipSourceColumns(myIndex))).Copy
wsDest.Cells(3, ipDestColumns(myIndex)).PasteSpecial xlPasteAll

Next

End Sub

关于excel - 仅将二维数组的某些元素/列写回工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61984133/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com