循环代码保持从文件夹中的相同Excel电子表格复制

时间:2014-08-01 11:43:51

标签: excel excel-vba vba

所以我试图在文件夹(文件名和路径)中创建一个excel文件列表,然后使用For循环将指定的工作表复制并粘贴到excel工作簿中指定工作表中列出的所有文件包含宏。到目前为止,一切都有效,除了相同的文件不断被复制和粘贴而不是所有文件。宏循环的次数正确,但它没有使用所有的excel文件。

以下是代码:

列出文件夹

中文件的第一部分
Private Sub btn_LeaveReport()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("D:\Administration\Time Sheets")
i = 2
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
    'print file name
    Cells(i + 1, 2) = objFile.Name
    'print file path
    Cells(i + 1, 3) = objFile.Path
    i = i + 1
Next objFile
End Sub

这是循环的一部分

Private Sub btn_PullData()
'Declared Variables
Dim wbk As Workbook
Dim i As Integer
Dim StartAt As Integer
Dim EndAt As Integer
Dim CopyPath As String
Dim CopyPathRow As Integer
Dim iRow As Integer

'Ranges
StartAt = 1
EndAt = Val(ThisWorkbook.Worksheets("LeaveReport").Range("A1"))
CopyPathRow = 3
CopyPath = ThisWorkbook.Worksheets("LeaveReport").Range("C" & CopyPathRow)
iRow = 3

'Loop de loop
For i = StartAt To EndAt
    Application.ScreenUpdating = False
    Set wbk = Workbooks.Open(CopyPath)
    Sheets("TIMESHEET").Select
    Range("C12:S34").Select
    Selection.Copy

    ThisWorkbook.Activate
    Sheets("Pastebin").Select
    Range("a" & iRow).PasteSpecial Paste:=xlPasteValues
    Application.CutCopyMode = False

    iRow = iRow + 39
    CopyPathRow = CopyPathRow + 1
    wbk.Close True
Next i

Sheets("Pastebin").Select
Range("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Application.ScreenUpdating = True
MsgBox "Timesheet Data Imported"
End Sub

根据错误的来源,即使用相同的文件,我猜测问题在于具有以下内容的部分:

CopyPath = ThisWorkbook.Worksheets(“LeaveReport”)。范围(“C”和CopyPathRow)

并且“假设”通过以下方式在For循环中更新:

CopyPathRow = CopyPathRow + 1

1 个答案:

答案 0 :(得分:0)

移动线

CopyPath = ThisWorkbook.Worksheets("LeaveReport").Range("C" & CopyPathRow)

在循环内部,CopyPath的值永远不会被更改,但CopyPathRow的值是。

编辑:我也不会调用此递归。