【发布时间】:2012-06-26 15:28:59
【问题描述】:
我正在尝试用一年中的月份填充 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 次。我自己可能正在寻求解决方案,但欢迎任何 cmets。
【问题讨论】:
-
我正在准备答案,但我首先有问题。每个工作簿的月份名称是否总是相同的顺序?那么一月、二月、三月,还是顺序取决于 mnth 是多少?
-
文件夹中的每个工作簿都是针对特定月份的。在每个数据中,我稍后将复制到这个主电子表格(EOYR - 年终报告)。这有帮助吗?
-
仅供参考,Dir() 函数非常笨重。有一个 FileSystemObject 对象,它对于像这样的导航/文件操作要好得多。您需要添加对 MicroSfot Scripting Runtime 的引用才能使用它。
-
+1 将查看 FileSystemObject。