Forum Discussion

TTC-BlueHill1's avatar
TTC-BlueHill1
Copper Contributor
May 01, 2024

VBA copy data from another workbook into current workbook (specific tab)

Hello, I have my target workbook called "Troy Corporation Carrier Review March 2024.xlsx" and there's tab name call 'Detail". My target workbook is locate in the network folder which I am an admin a...
  • HansVogelaar's avatar
    HansVogelaar
    May 01, 2024

    TTC-BlueHill1 

    A correction:

    Sub ImportData()
        Dim wbkSource As Workbook
        Dim wshSource As Worksheet
        Dim lngLastSourceRow As Long
        Dim wbkTarget As Workbook
        Dim wshTarget As Worksheet
        Dim lngTargetRow As Long
        Dim strFolder As String
        Dim strFile As String
    
        Application.ScreenUpdating = False
        Set wbkTarget = Workbooks("Troy Corporation Carrier Review March 2024.xlsx")
        Set wshTarget = wbkTarget.Worksheets("Detail")
        On Error Resume Next
        lngTargetRow = 3
        ' Path of the subfolder with the source workbooks
        strFolder = "N:\MyFolder\MySubfolder\"
        strFile = Dir(strFolder & "*.xls*")
        Do While strFile <> ""
            Set wbkSource = Workbooks.Open(Filename:=strFolder & strFile, ReadOnly:=True)
            Set wshSource = wbkSource.Worksheets(1)
            lngLastSourceRow = wshSource.Range("A:AA").Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
            wshSource.Range("A2:AA" & lngLastSourceRow).Copy Destination:=wshTarget.Range("E" & lngTargetRow)
            Application.CutCopyMode = False
            wbkSource.Close SaveChanges:=False
            lngTargetRow = lngTargetRow + lngLastSourceRow - 1
            strFile = Dir
        Loop
        Application.ScreenUpdating = True
    End Sub

Resources