我试图用一年中的几个月来填充A2:A13。显然我可以输入几个月,但是我使用从一个文件夹中的12个工作簿派生的字符串来填充它们。我之所以这样做,是因为我还要用其他数据填充其他列,因此相同的方法将适用,我认为这是一项有用的练习。
代码设置为循环遍历包含文件夹中的所有工作簿,我希望它使用for循环填充A2:A13,其中包含从每个工作簿派生的字符串,如下所示。然而,目前每个细胞都是12月份。
Option Explicit
Sub CompileRandomCheckingData()
Dim MyPath As String, strfilename As String, mnth As String
Dim EOYR As Workbook, indv As Workbook
Dim psdsht As Worksheet, eoyrsht As Worksheet
Dim LRow As Long
Dim i As Integer
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'--> Set Containing Folder
MyPath = "C:\Documents and Settings\alistairw\Desktop\temppsdreports2011"
strfilename = Dir(MyPath & "\*.xls", vbNormal)
'--> If folder is empty then exit
If Len(strfilename) = 0 Then Exit Sub
Do Until strfilename = ""
'--> Define each workbook
Set EOYR = ThisWorkbook
Set eoyrsht = EOYR.Sheets("Sheet1")
Set indv = Application.Workbooks.Open("C:\Documents and Settings\alistairw\Desktop\temppsdreports2011\" & strfilename)
'--> Working with individual workbooks
Set psdsht = indv.Sheets("Sheet1")
With psdsht
LRow = .Range("D" & Rows.Count).End(xlUp).Row
End With
'--> Set Month from Workbook Title
mnth = Split(strfilename, " ")(3)
For i = 2 To 13
With eoyrsht
.Cells(i, 1) = mnth
End With
Next
'--> Copy No. Items
'--> Copy Gross Value
'--> Copy Final Error Value
'--> Tidy Up
indv.Close
strfilename = Dir()
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
修改
我理解为什么他们都被填充了12月,因为For循环总共运行了12次主循环。我可能正在接近解决方案,但欢迎任何评论。
答案 0 :(得分:2)
这是有道理的:
For i = 2 To 13
With eoyrsht
.Cells(i, 1) = mnth
End With
Next
使用相同的mnth
从第2行到第13行填充第一列,这是您在Do Until循环中打开的电子表格的月份。因此,最后一个循环,可能会打开12月的电子表格,将覆盖您之前所做的任何事情。
你可能意味着:
i = 2
Do Until ...
....
With eoyrsht
.Cells(i, 1) = mnth 'puts the month of the spreadsheet you are looking at in line i
End With
i = i + 1 'increments i for the next spreadsheet's month
....
Loop