I am looking for some excel help with Visual Basic and macros. I can code in excel but I’m absolutely stumped on something for work. Here’s what I need:
I need a button on the bottom of an excel sheet that when pressed takes a predetermined group of cells in said sheet, opens up a new word document, pastes said cells and formats them to all fit width wise on a word document (if the length takes up more than one page that’s fine). If you could also just supply said code that would really help. I’m absolutely slammed on all fronts right now. .
My goal is to make this as user friendly so the rest of my department can use said document.
Thanks in advance. 🙂
I’ve tried a couple different codes. The closest I got to solving said problem was the button needing the user to select the certain cells and then it did what I wanted but wouldn’t format it right to fit in word. I also don’t want to have to have my coworkers do anything other than click the button.
This is what I have so far. It doesn’t do anything. Doesn’t even give me errors.
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
Alison Bentle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2