Private Sub CommandButton4_Click() Dim sourceWorkbook As Workbook Dim destWorkbook As…
- User
Private Sub CommandButton4_Click() 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
If you want the data to start pasting from column B (which is the second column), but you're currently observing it starts pasting from column C, the issue likely lies in this line:
vbasourceSheet.UsedRange.Copy Destination:=destSheet.Cells(2, 2) ' Starts pasting from B4The comment in your code suggests an intention to start pasting from "B4", but it seems there might be a misunderstanding regarding the
Cellsmethod.Cells(row, column)takes two arguments where the first is the row index and the second is the column index. Given the referenceCells(2, 2), it correctly identifies cell "B2", not "B4" or "C2".If your goal is to start pasting from "B1" (the very beginning of column B), simply adjust the column index to 1, keeping the row index as 1 if starting from the first row:
vbasourceSheet.UsedRange.Copy Destination:=destSheet.Cells(1, 2)