【问题标题】:Populating column using a for loop使用 for 循环填充列
【发布时间】: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。

标签: excel for-loop vba


【解决方案1】:

有道理:

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

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

【讨论】:

  • 这很好用,我意识到为什么会这样,但在您回答时不知道如何解决。谢谢。我会接受的。
猜你喜欢
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 2021-07-06
  • 2019-06-12
  • 1970-01-01
相关资源
最近更新 更多