I need to have a button with a macro that copies a range of cells and their formatting/make it autofit width wise on an doc and pasted them into a new word document when the button is clicked.
This is what I have. It doesn’t do anything. Not even showing an error.
Sub RectangleRoundedCorners1_Click()
On Error GoTo ClearError
Const wdFolderPath As String = "C:Test"
Const wdFileName As String = "Test.docx"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets("Format")
Dim rg As Range: Set rg = ws.Range("B29:B119")
' Reference the Word Application.
Dim wdApp As Word.Application
Dim WordWasClosed As Boolean
' 1. Attempt to create a reference (check if it is open).
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
On Error GoTo ClearError
' 2. If no reference, open and create a reference to it.
If wdApp Is Nothing Then ' Word is closed
Set wdApp = New Word.Application
WordWasClosed = True
wdApp.Visible = True ' uncomment when done testing
'Else ' Word is open and referenced; do nothing
End If
' Open and reference a new word document.
Dim wdDoc As Word.Document: Set wdDoc = wdApp.Documents.Add
' Copy/Paste.
rg.Copy
wdDoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=True, _
RTF:=False
Application.CutCopyMode = False
' Continue modifying the Word document...
SafeExit:
On Error Resume Next
' Save and close the Word document.
If Not wdDoc Is Nothing Then ' overwrite without confirmation
wdDoc.SaveAs2 wdFolderPath & wdFileName, wdFormatDocumentDefault
End If
' Quit the Word application...
If WordWasClosed Then ' ... if it initially was closed
If Not wdApp Is Nothing Then wdApp.Quit
'Else ' ... if it initially was open, don't quit; do nothing
End If
On Error GoTo 0
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume SafeExit
End Sub
New contributor
Alison Bentle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.