Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sub CopyRangeToNewWorkbookNoPrompts()
- Dim sourceRange As Range
- Dim newWorkbook As Workbook
- Dim targetWorksheet As Worksheet
- Dim fileSaveName As String
- Dim timeStamp As String
- ' Use the current selected range
- Set sourceRange = Selection
- ' Check if a range is selected
- If sourceRange Is Nothing Then
- MsgBox "No range selected. Exiting."
- Exit Sub
- End If
- ' Create a new workbook
- Set newWorkbook = Workbooks.Add
- Set targetWorksheet = newWorkbook.Worksheets(1)
- ' Copy the selected range (including data, formatting, and column sizes)
- sourceRange.Copy
- ' Paste the copied range to the new workbook
- With targetWorksheet.Cells(1, 1)
- .PasteSpecial Paste:=xlPasteAll
- .PasteSpecial Paste:=xlPasteColumnWidths
- End With
- ' Clear clipboard
- Application.CutCopyMode = False
- ' Generate the file name with date stamp
- timeStamp = Format(Now(), "yyyy-mm-dd-hhmmss")
- fileSaveName = ThisWorkbook.Path & "\" & ThisWorkbook.Name & "_" & timeStamp & ".xlsx"
- ' Save the new workbook and close it
- newWorkbook.SaveAs Filename:=fileSaveName
- newWorkbook.Close SaveChanges:=True
- MsgBox "New file saved as: " & fileSaveName
- End Sub
Add Comment
Please, Sign In to add comment