Excel VBA从其他Excel文件收集数据并将其粘贴到Masterfile中

时间:2019-04-11 01:20:13

标签: excel vba

我是C#程序员,是Excel VBA的新手,在这里我处于极限。 我不明白如何将不同文件中的数据复制并粘贴到一个Masterfile中。

我要从用户定义文件夹中的Excel文件中收集所有数据。这些数据始终存储在excel文件中。 并且总是从D列开始,直到从第六行到最后一行的最后一列。

因此,我想首先获取父目录,在该目录中我可以找到此父文件夹中的所有文件。 之后,我开始执行CollectSubdata过程。

所以我的方法是从每个子文件中复制范围并将其粘贴到主文件的第六行和最后一列

Private Sub CollectData()

Dim MasterWorkbook As Workbook
Set MasterWorkbook = Workbooks("Masterfile.xlsm")

Dim Folderpath As String
'Get Folder which contains all Data
Folderpath = UserGetFolder & "\"

Dim obj As Object
Dim ParentFolder As Object
Dim Files As Object

Set obj = CreateObject("Scripting.FileSystemObject")
Set ParentFolder = obj.GetFolder(Folderpath)
Set Files = ParentFolder.Files

Application.ScreenUpdating = False

'Loop through all folder now
Dim subfile As Object
For Each subfile In ParentFolder.Files

'Start Data Collection
Call CollectSubdata(subfile)

Next subfile


End Sub

这是我的子过程

Private Sub CollectSubdata(ByRef subfile As Object)

' Do Data collection here
Dim subwb As Workbook
Dim LastColumn As Double
Dim LastRow As Double
Dim LastMasterCol As Double

LastMasterCol = MasterWorkbook.Sheets(1).Cells(6, Columns.Count).End(xlToLeft).Column

Set subwb = Workbooks.Open(subfile)
LastColumn = subwb.Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
LastRow = subwb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row

'Copy all necessary entries
subwb.Sheets(1).Range(Cells(6, 4), Cells(LastRow, LastColumn)).Copy

'Paste into Masterfile
MasterWorkbook.Sheets(1).Cells(6, LastMasterCol).PasteSpecial Paste:=xlPasteAll

subwb.Close
End Sub

还有我的用户定义文件夹

Function UserGetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    UserGetFolder = sItem
    Set fldr = Nothing
End Function

我不明白VBA的要旨是使用这些对象和方法。

1 个答案:

答案 0 :(得分:0)

仅在定义变量的上下文中存在变量。在您的情况下,指针masterworkbook在例程CollectData中定义,因此它仅存在于该例程中。为了将其放入CollectSubData中,您需要将对其的引用作为子例程的参数传递,或者在模块级别定义变量,以便该变量在该模块内的所有例程中都存在。前者是一种较好的做法,因此您应将CollectSubData定义为

 Private Sub CollectSubdata(ByRef subfile As Object, ByRef MasterWorkbook As Workbook) 

并命名为

 'Start Data Collection
 CollectSubdata(subfile,MasterWorkbook)

请注意,在这种情况下不需要致电(尽管它本身并没有错)