Sub CopyDataAndRenameAutomatically() Dim folderPath As String Dim xlsxFile As String,…
- User
Sub CopyDataAndRenameAutomatically()
Dim folderPath As String Dim xlsxFile As String, xlsmFile As String Dim wbSource As Workbook, wbDestination As Workbook Dim wsSource As Worksheet, wsDestination As Worksheet Dim lastRow As Long, lastColumn As Long Dim newName As String ' Automatically getting the folder where this workbook is saved folderPath = ThisWorkbook.Path ' Ensure folderPath ends with a backslash If Right(folderPath, 1) <> "" Then folderPath = folderPath & "" 'Finding the files in the folder xlsxFile = Dir(folderPath & "*.xlsx") xlsmFile = "MARKER-REPORT.xlsm" 'Exiting the Sub if the .xlsx file is not found If xlsxFile = "" Then MsgBox "No .xlsx file found in the directory.", vbExclamation Exit Sub End If 'Opening both workbooks Set wbSource = Workbooks.Open(folderPath & xlsxFile) Set wbDestination = Workbooks.Open(folderPath & xlsmFile) 'Setting up the source and destination worksheets Set wsSource = wbSource.Sheets(1) Set wsDestination = wbDestination.Sheets(1) 'Finding the last row and column with data in the source sheet lastRow = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row lastColumn = wsSource.Cells(1, wsSource.Columns.Count).End(xlToLeft).Column 'Copying all data from the source sheet to destination sheet wsSource.Range(wsSource.Cells(1, 1), wsSource.Cells(lastRow, lastColumn)).Copy wsDestination.Cells(1, 1).PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False ' To clear clipboard and remove marching ants ' Close the source workbook without saving changes wbSource.Close SaveChanges:=False ' Save the destination workbook with the new name newName = Replace(xlsxFile, ".xlsx", ".xlsm") 'Creating the new name based on the .xlsx filename wbDestination.SaveAs Filename:=folderPath & newName, FileFormat:=xlOpenXMLWorkbookMacroEnabled ' Close the destination workbook wbDestination.Close SaveChanges:=False MsgBox "Data copied and file renamed to " & newName, vbInformationEnd Sub no.xslx file found
- Assistant
Your script is designed to automatically copy data from a file in a specific folder to a predefined file named "MARKER-REPORT.xlsm", also located in the same folder. After copying the data, it saves the destination workbook () with a new name that derives from the original file but with the extension, and then closes it without saving any further changes.
- User
same
- Assistant