• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

change VBA code so i can rename folder path from cell A1

shili12

Member
I want to have a simpler way of renaming folder path, maybe one can type into cell A1 the name of folder to import and the code changes,
here folderPath = "C:\Users\S.Lakh\Downloads\allied\"

Code:
Sub ImportWorkbooks()
    Dim folderPath As String
    Dim fileName As String
    Dim wbTarget As Workbook
    Dim wbSource As Workbook
    Dim wsTarget As Worksheet
    Dim wsSource As Worksheet
    Dim lastRow As Long
    
    ' Set the folder path
    folderPath = "C:\Users\S.Lakh\Downloads\allied\"
    
    ' Create a new workbook to consolidate the data
    Set wbTarget = Workbooks.Add
    Set wsTarget = wbTarget.Sheets(1)
    
    ' Loop through all files in the folder
    fileName = Dir(folderPath & "*.xlsx")
    Do While fileName <> ""
        ' Open each workbook in the folder
        Set wbSource = Workbooks.Open(folderPath & fileName)
        Set wsSource = wbSource.Sheets(1)
        
        ' Find the last row in the target workbook
        lastRow = wsTarget.Cells(wsTarget.Rows.Count, 1).End(xlUp).Row
        
        ' Copy data from source workbook to target workbook
        wsSource.UsedRange.Copy wsTarget.Cells(lastRow + 1, 1)
        
        ' Close the source workbook
        wbSource.Close False
        
        ' Get the next file in the folder
        fileName = Dir
    Loop
    
    ' Save and close the target workbook
    wbTarget.SaveAs folderPath & "Consolidated_Workbooks.xlsx"
    wbTarget.Close False
    
    MsgBox "Workbooks have been consolidated successfully!", vbInformation
End Sub
 

Attachments

  • Consolidated_Workbooks.xlsm
    18.5 KB · Views: 2
Code:
folderPath = [A1].Value
And In cell A1 path
C:\Users\S.Lakh\Downloads\allied\ (without the brackets)
 
How to choose a folder via a VBA double click event on a specific cell :​
 
Back
Top