Excel 使用for循环填充列
我试图用一年中的月份填充A2:A13。显然,我可以只键入月份,但我使用从文件夹中的12本工作簿派生的字符串填充它们。我这样做是因为我还将用其他数据填充其他列,所以同样的方法将适用,我认为这是一个有用的练习 代码设置为循环包含文件夹中的所有工作簿,我希望它使用从每个工作簿派生的字符串填充A2:A13,使用for循环,如下所示。然而,目前每个单元都只填充了12月Excel 使用for循环填充列,excel,for-loop,vba,Excel,For Loop,Vba,我试图用一年中的月份填充A2:A13。显然,我可以只键入月份,但我使用从文件夹中的12本工作簿派生的字符串填充它们。我这样做是因为我还将用其他数据填充其他列,所以同样的方法将适用,我认为这是一个有用的练习 代码设置为循环包含文件夹中的所有工作簿,我希望它使用从每个工作簿派生的字符串填充A2:A13,使用for循环,如下所示。然而,目前每个单元都只填充了12月 Option Explicit Sub CompileRandomCheckingData() Dim MyPath As S
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
编辑:
我理解为什么它们都被十二月填充,因为For循环与主循环一起总共运行了12次。我自己可能正在寻求解决方案,但欢迎发表任何意见。这很有意义:
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
我正在准备一个答案,但我先有个问题。每个工作簿的月份名称顺序是否始终相同?因此,1月、2月、3月或顺序取决于mnth是什么?文件夹中的每个工作簿都是特定月份的。在每个数据中,我稍后将复制到此主电子表格(EOYR-年终报告)。这有用吗?仅供参考,Dir()函数非常笨重。有一个FileSystemObject对象,对于这样的导航/文件操作,它要好得多。您需要添加对MicrosoftScripting运行时的引用才能使用它。+1将查看FileSystemObject。这非常有效,我知道了发生的原因,但在您回答时不知道如何解决它。谢谢我会在我能接受的时候接受。