简体   繁体   中英

How do I copy a range from one workbook to another in excel WITHOUT having to name it in VBA?

I'm looking for assistance regarding how to write a VBA command that allows me to copy a range of cells from different workbooks onto one master sheet. Let me explain further.

Everyday I receive a new excel document from my clients named based on the date it was uploaded ie. September 18, 2018 file would be called A20180918.

Once i've received a week's worth of excel files (A20180918-A20180921), I then have to copy certain information from the original uploaded file to a master tracking sheet.

So, my hurdle is such that each time I record my actions into a macro, the code includes the file name which then creates a subscript error when it's run on the next day's file.

So here's an example below of the code I have this far:

Sub CopyRange()

CopyRange Macro

'This is the line of the code that's causing problems given it's a specified workbook name 
'and when I try to open tomorrow's workbook i'll run into the subscript error.
Windows("A20180914.xls").Activate

Range("A2:B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("Master Sheet.xlsm").Activate
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End Sub

Thank you!

Here's two solutions. One to scan an Directory for files, and the other to select files. I see they've both been suggested in the comments already. :p

Sub Test()
    ' If you want to scan an "unprocessed files" directory
    'Call ScanDir("C:\Test\")

    ' If you want to select files to process
    Call SelectFiles
End Sub

Private Sub ScanDir(ByVal DirPath As String)
    Dim oCurFile As String
    oCurFile = Dir(DirPath)
    Do While oCurFile <> ""
        ' Add the work to the file here
        ' Filename: DirPath & oCurFile

        oCurFile = Dir()
    Loop
End Sub

Private Sub SelectFiles()
    Dim oFileDialog As FileDialog
    Set oFileDialog = Application.FileDialog(msoFileDialogFilePicker)
    oFileDialog.AllowMultiSelect = True

    If oFileDialog.Show = -1 Then
        Dim oFile As Variant

        For Each oFile In oFileDialog.SelectedItems
            ' Add the work to the file here
            ' Filename: oFile
        Next
    End If

End Sub

This will do it, you just need to supply the sheet name and ranges where noted:

Sub copyRange()

    'File system variables
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim myDir As String
    Dim Mask As String

    'Workbook variables
    Dim wb As Workbook
    Dim sh As Worksheet

    myDir = "C:\Users\Guest\Desktop" 'Insert the path where your incoming files are stored.

    Mask = "*.xl??" 'This makes it so it only looks at Excel files.

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.getFolder(myDir)

    For Each objFile In objFolder.Files

        If LCase(objFile.Name) Like LCase(Mask) Then

            Set wb = Workbooks.Open(myDir & "\" & objFile.Name, , True) 'This is set to open in read only, to avoid issues with the file already being open

            'The ranges you are copying/pasting are vague, supply the sheet names and ranges below

            'Get Copy range with dynamic number of rows.
            With wb.Sheets("Sheet1").Range("A2:B2") '<---- Specify Sheet/Range
                Set copyRange = .Resize(.End(xlDown).Row, 2)
            End With

            'Get next available row in paste range.
            With ThisWorkbook.Sheets("Sheet1").Range("G:H") '<---- Specify Sheet/Range
                Set pasteRange = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0)
            End With

            copyRange.Copy pasteRange

            wb.Close False

        End If

    Next objFile

End Sub

By the looks of it you have all the workbooks open when you run the code - there are ways to have the code open each workbook in a certain folder, or ask the user to select them.
While writing this other answers have given the code for selecting files from folders.

Each workbook in the Excel Application is held in a collection of workbooks. The good thing about collections is you can step through them without know the specifics before you get there.

The code below will print the name of each workbook you have open into the immediate window. Note - these are in the same instance of Excel. If you open Excel a second time then any workbooks in that application will be in a different collection.
You don't really need the Application but I left it in to make things a bit clearer.

Sub Test()

    Dim bk As Workbook

    For Each bk In Application.Workbooks
        Debug.Print bk.Name
    Next bk

End Sub  

This is the full code - note that nothing is Select ed.

Sub Test()

    Dim bk As Workbook
    Dim Master As Workbook
    Dim LastCell As Range

    Set Master = Workbooks("Master Sheet.xlsm")

    For Each bk In Application.Workbooks
        'Checks the middle part of the file name - should be a number.
        'Better ways to check the file name are available.
        If IsNumeric(Mid(bk.Name, 3, 8)) Then

            'Copy date from Sheet1.  It's assumed each row in
            'column B is populated and figures out the last cell from there.
            With bk.Worksheets("Sheet1")
                Set LastCell = .Cells(.Rows.Count, 2).End(xlUp)
                .Range("A1", LastCell).Copy
            End With

            'Pastes the results to Sheet1 in the Master workbook.
            'The last cell containing data in column A is found and
            'then offset by 1 row.
            With Master.Worksheets("Sheet1")
                .Range("A" & .Rows.Count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValues
            End With

        End If
    Next bk

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM