0

我正在尝试用一年中的月份填充 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 次。我自己可能正在寻求解决方案,但欢迎提出任何意见。

4

1 回答 1

2

那讲得通:

For i = 2 To 13
    With eoyrsht
        .Cells(i, 1) = mnth
    End With
Next

使用相同的 填充第 2 行到第 13 行的第一列mnth,这是您在“直到”循环中打开的电子表格的月份。因此,可能会打开 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
于 2012-06-26T15:33:58.880 回答