Dim sourceWorkbook As Workbook Dim destWorkbook As Workbook Dim sourceSheet As Worksheet…
- User
Dim sourceWorkbook As Workbook Dim destWorkbook As Workbook Dim sourceSheet As Worksheet Dim destSheet As Worksheet Dim folderPath As String Dim sourceFileName As String Dim sourceFilePath As String
code' Dynamically get the folder path of the workbook containing this script (.xlsm) ' and ensure it ends with a backslash folderPath = ThisWorkbook.Path If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\" End If ' Get the name of the first .xlsx file in the folder sourceFileName = Dir(folderPath & "*.xlsx") ' Check if an .xlsx file was found If sourceFileName = "" Then MsgBox "No .xlsx file found in the same folder." Exit Sub End If ' Construct the full file path for the .xlsx file sourceFilePath = folderPath & sourceFileName ' Set the destination workbook and sheet ' ThisWorkbook refers to the workbook containing this script (.xlsm) Set destWorkbook = ThisWorkbook Set destSheet = destWorkbook.Sheets(1) ' Adjust as needed if copying to a different sheet ' Attempt to open the source .xlsx file On Error Resume Next ' In case the file doesn't open Set sourceWorkbook = Workbooks.Open(sourceFilePath) On Error GoTo 0 ' Turn back on regular error handling after attempt to open ' Check if the workbook was successfully opened If sourceWorkbook Is Nothing Then MsgBox "Failed to open the .xlsx file." Exit Sub End If ' Set the source sheet (assuming data is on the first sheet) Set sourceSheet = sourceWorkbook.Sheets(1) ' Copy the used range from the source sheet to the destination sheet sourceSheet.UsedRange.Copy Destination:=destSheet.Cells(2, 2) ' Starts pasting from B4 ' Close the source workbook without saving changes sourceWorkbook.Close SaveChanges:=False MsgBox "Data copied successfully from " & sourceFileName - Assistant
- User
data in destination must be pasted starting with row b
- Assistant