VBA循环并行通过数组

我想创build一个循环通过特定的表和专门链接,但这不起作用,我误解如何使用数组?

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))以并行方式循环,其中第一个作为源表单,第二个作为目标表单的列号。 任何帮助?

您不能创build一个数组并将其视为一个Worksheet。 而且你不需要把这两个数组放在一个数组中。 最后,它看起来像你想要做的事情:

 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 

variables声明big, rc, sr As Worksheet意思是sr As Worksheet ,而rcsrVariant 。而且,你不会在任何地方Dim 。 如果您在代码的顶部使用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