VBA通过数组并行循环

时间:2017-12-11 10:52:22

标签: arrays excel vba excel-vba multidimensional-array

我正在尝试通过专门链接的特定表单和列来创建循环,但这不起作用,我是否误解了如何使用数组?

Sub test()

Dim wb As Workbook, big, rc, sr  As Worksheet, rejcheck, copyto, arr As variant
Set wb = ActiveWorkbook
Set big = wb.Sheets("BIG")
Set oou = wb.Sheets("OOU")
Set sr = wb.Sheets("SR")

rejcheck = Array(big, sr, oou)
copyto = Array(47, 23, 58)
arr = Array(rejcheck, copyfrom)

For Each x In arr
    With rejcheck
        .Range("a2").Copy wb.Sheets("other sheet").Cells(1, copyto)
        wb.Sheets("other sheet").Cells(1, copyto).Offset(0, 1).Value = .Name
    End With
Next x

End Sub

基本上我希望通过这些关联值((big, 47),(sr,23),(oou,58))以并行方式循环,其中第一个作为源表,第二个是目标表的列号。 有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

变量声明big, rc, sr As Worksheet表示sr As Worksheet,而rcsr表示Variant。此外,您不是Dim {1}} x任何地方。如果您在代码顶部使用Option Explicit>> VBA编辑会尖叫"一个错误。

下一步:如果您想使用arr,稍后并行循环,则需要将arr定义并设置为二维数组,并向其中读取rejcheckcopyto个数组值。

<强> 代码

Option Explicit

Sub test()

Dim wb As Workbook
Dim big As Worksheet, rc As Worksheet, sr As Worksheet, oou As Worksheet
Dim rejcheck As Variant, copyto As Variant, arr As Variant, x As Variant
Dim i As Long

Set wb = ActiveWorkbook
Set big = wb.Sheets("BIG")
Set oou = wb.Sheets("OOU")
Set sr = wb.Sheets("SR")

rejcheck = Array(big, sr, oou)
copyto = Array(47, 23, 58)

' define 2-D array according to size of rejcheck array
ReDim arr(0 To UBound(rejcheck), 0 To 1)

' loop through the elements and insert to 2-d array (1 of sheets, second of numeric values)
For i = LBound(rejcheck) To UBound(rejcheck)
    Set arr(i, 0) = rejcheck(i) ' <-- use Set when adding Worksheet object
    arr(i, 1) = copyto(i)
Next i

For i = LBound(arr, 1) To UBound(arr, 1)
    With arr(i, 0)
        .Range("A2").Copy wb.Sheets("other sheet").Cells(1, arr(i, 1))
        wb.Sheets("other sheet").Cells(1, arr(i, 1)).Offset(0, 1).Value = .Name
    End With
Next i

End Sub

答案 1 :(得分:1)

您无法创建数组并将其视为工作表。而且您不需要将两个数组放在一个数组中。最后,看起来你想做类似的事情:

Option Base 0

Sub test()
  Dim wb As Workbook, big, oou, sr  As Worksheet, rejcheck, copyto, x As Variant
  Dim i As Integer
  Set wb = ActiveWorkbook
  Set big = wb.Sheets("BIG")
  Set oou = wb.Sheets("OOU")
  Set sr = wb.Sheets("SR")

  rejcheck = Array(big, sr, oou)
  copyto = Array(47, 23, 58)

  For i = 0 To UBound(rejcheck)
    With rejcheck(i)
      .Range("a2").Copy wb.Sheets("other sheet").Cells(1, copyto(i))
      wb.Sheets("other sheet").Cells(1, copyto(i)).Offset(0, 1).Value = .Name
    End With
  Next
End Sub