vba 基于数组的读取、转换和粘贴

vba read, transform and paste based on arrays

我有一个主要的 sheet,其中包含大约 2800 个条目的数据集,需要构建新的 sheets,其中包含主要数据的一个子集,没有一些键。我通过范围直接访问完成了这一切,但速度太慢了。我现在尝试用数组重建逻辑。

我的目标是 (1) 将范围读入变体主数组 (2) 遍历这个主数组 (3) 基于 criteria/keys 使用主数组的子集构建新数组 (4) 将每个新的 "subset"-arrays 粘贴到新的 sheets

一 (1) 个我

 Dim varray As Variant
    varray = Sheets("MAINSHEET").Range("B2:Q" & Sheets("MAINSHEET").Cells(Rows.Count, "B").End(xlUp).Row).Value

对于 (2) & (3) 我有这样的东西

For masterCounter = 1 To UBound(varray, 1)

  If InStr(1, currentUID, "KEY_XYZ", 1) Then
        subarray1(currentRow, 1) = varray(currentRow, 1)
        subarray1(currentRow, 2) = Trim(varray(currentRow, 2))
        subarray1(currentRow, 3) = varray(currentRow, 5)
 End If

      masterCounter = masterCounter + 1
Next

但是,现在我 运行 在用主数组中的值填充新的子集数组时遇到了一些类型不匹配错误。

有什么解决办法吗?

谢谢

在给它赋值之前,你需要重新调整 subarray1

在您的 For ... Loop:

之前插入此行
    ReDim subarray1(LBound(varray) To UBound(varray), 1 To 3)

我假设 subarray1 应该有 3 列和与 varray 一样多的行。如果您需要其他尺寸,您需要相应地更改它。

您的代码不完整,无法提供全面帮助(例如,您如何声明和设置 currentRow),但这里有些东西可能会有所帮助。

你的数组声明需要方括号...

    Dim varray() As Variant

此外,我建议更详细一些。

赞:

Sheets("MAINSHEET").Range("B2:Q" & Sheets("MAINSHEET").Cells(Rows.Count, "B").End(xlUp).Row).Value

将 "Rows.Count" 替换为“.Rows.Count”

With Sheets("MAINSHEET")
    .Range("B2:Q" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
end with 



Sub fred()

    Dim MyRange As Range
    Dim varray() As Variant
    Dim subarray1() As Variant

    With Sheets("MAINSHEET")
        Set MyRange = .Range("B2:Q" & .Cells(.Rows.Count, "B").End(xlUp).Row)

        Debug.Print MyRange.Address

        varray = MyRange

    End With

    For masterCounter = 1 To UBound(varray, 1)

        Debug.Print varray(currentRow, 1)

         If InStr(1, currentUID, "KEY_XYZ", 1) Then
               subarray1(currentRow, 1) = varray(currentRow, 1)
               subarray1(currentRow, 2) = Trim(varray(currentRow, 2))
               subarray1(currentRow, 3) = varray(currentRow, 5)
        End If

          masterCounter = masterCounter + 1
    Next


End Sub