Guest User

VBA macro new sheet

a guest
Apr 9th, 2023
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VisualBasic 1.26 KB | Source Code | 0 0
  1. Sub CopyRangeToNewWorkbookNoPrompts()
  2.  
  3.     Dim sourceRange As Range
  4.     Dim newWorkbook As Workbook
  5.     Dim targetWorksheet As Worksheet
  6.     Dim fileSaveName As String
  7.     Dim timeStamp As String
  8.  
  9.     ' Use the current selected range
  10.    Set sourceRange = Selection
  11.  
  12.     ' Check if a range is selected
  13.    If sourceRange Is Nothing Then
  14.         MsgBox "No range selected. Exiting."
  15.         Exit Sub
  16.     End If
  17.  
  18.     ' Create a new workbook
  19.    Set newWorkbook = Workbooks.Add
  20.     Set targetWorksheet = newWorkbook.Worksheets(1)
  21.  
  22.     ' Copy the selected range (including data, formatting, and column sizes)
  23.    sourceRange.Copy
  24.  
  25.     ' Paste the copied range to the new workbook
  26.    With targetWorksheet.Cells(1, 1)
  27.         .PasteSpecial Paste:=xlPasteAll
  28.         .PasteSpecial Paste:=xlPasteColumnWidths
  29.     End With
  30.  
  31.     ' Clear clipboard
  32.    Application.CutCopyMode = False
  33.  
  34.     ' Generate the file name with date stamp
  35.    timeStamp = Format(Now(), "yyyy-mm-dd-hhmmss")
  36.     fileSaveName = ThisWorkbook.Path & "\" & ThisWorkbook.Name & "_" & timeStamp & ".xlsx"
  37.  
  38.     ' Save the new workbook and close it
  39.    newWorkbook.SaveAs Filename:=fileSaveName
  40.     newWorkbook.Close SaveChanges:=True
  41.  
  42.     MsgBox "New file saved as: " & fileSaveName
  43.  
  44. End Sub
  45.  
Add Comment
Please, Sign In to add comment