我有一个脚本,该脚本循环遍历文件夹路径,并将一堆单个报告合并为一个主报告,然后将整个数组的已编译数组打印到一个主工作表上。它工作良好,在标题行之后打印,但是在直到最后一次编译的报告的最后一行数据为止打印数组。数组索引中有148行,但只打印其中的147行,并退出子表。
在这里,我要制作第二个数组以一次打印它,也许是在这里的某个地方将其切断?
ReDim varArray2(1 To UBound(varArray, 2), 1 To UBound(varArray, 1))
With Workbooks("Retail_Goal_Report.xlsm").Worksheets("Merged Reports")
For j = 1 To UBound(varArray, 2)
For k = 1 To UBound(varArray, 1)
varArray2(j, k) = varArray(k, j)
Next
Next
.Range(.Cells(2, 1), .Cells(UBound(varArray, 2), UBound(varArray, 1))) = varArray2
End With
整个代码:
Option Explicit
Sub Sharepoint_Merge()
Dim k As Long, x As Long, j As Long ' counters
Dim varArray() As Variant
Dim varArray2() As Variant
ReDim varArray(1 To 23, 1 To 1)
Dim folderPath As String, filepath As String, filename As String
Dim wb As Workbook
Dim myvar As Variant
Dim myFolder As String
Dim i As Long
folderPath = "C:\merge\"
filepath = folderPath & "*.xlsx"
filename = Dir(filepath)
Call Ludicrous(True)
Do While filename <> ""
Set wb = Workbooks.Open(folderPath & filename)
With wb.Worksheets("Sheet1")
For j = 2 To .UsedRange.Rows.Count + 1
If .Cells(j, 1) <> "" Then
x = x + 1
ReDim Preserve varArray(1 To UBound(varArray, 1), 1 To x)
For k = 1 To UBound(varArray, 1)
varArray(k, x) = .Cells(j, k)
Next
End If
Next
End With
wb.Close
filename = Dir
Loop
ReDim varArray2(1 To UBound(varArray, 2), 1 To UBound(varArray, 1))
With Workbooks("Retail_Goal_Report.xlsm").Worksheets("Merged Reports")
For j = 1 To UBound(varArray, 2)
For k = 1 To UBound(varArray, 1)
varArray2(j, k) = varArray(k, j)
Next
Next
.Range(.Cells(2, 1), .Cells(UBound(varArray, 2), UBound(varArray, 1))) = varArray2
End With
myFolder = "C:\Retail-Goal\merge\"
myvar = FileList(myFolder, "*.xlsx")
For i = LBound(myvar) To UBound(myvar)
Kill myFolder & myvar(i)
Next
Call Ludicrous(False)
End Sub
答案 0 :(得分:0)
Nick Landa提交后,
.Range(.Cells(2, 1), .Cells(UBound(varArray, 2), UBound(varArray, 1))) = varArray2
应该是
.Range(.Cells(2, 1), 1 + .Cells(UBound(varArray, 2), UBound(varArray, 1))) = varArray2
您的数组为148行。如果未选择148行范围,则将仅输出所选内容,并中继其他所有内容。在这种情况下,由于您从第2行开始,一直到第148行,所以共有147行。
旁注:更好的方法是重命名迭代变量(而不是使用i
和j
来使用RowIterator和ColumnIterator,这样您就会更好地理解了上。
然后最后要优化代码的速度,而不是在专用的步骤中转置矩阵,然后将值发送到工作表,只需在专用指令中将值发送到工作表即可。
For RowIterator = 1 To UBound(varArray, 2)
For ColumnIterator = 1 To UBound(varArray, 1)
.Cells(1 + RowIterator, ColumnIterator) = varArray(ColumnIterator, RowIterator)
Next
Next
由于这种方法不涉及选择范围然后在其中复制数组,因此您不会遇到此问题。