I am writing a macro that will read an excel table and write the values in the table into an excel file. I would like the macro to take the values from column A and format them to Heading1 style, and the values from column B and format them to Heading2 style, and finally the values from column C should be just Normal style.
Sub magicmacro()
Dim rng As Range
Dim row As Range
Dim cell As Range
Set rng = Range("A1:D10")
'word file part
Dim DocApp As Object
Dim DocFile As Object
Dim DocName As String
On Error Resume Next
Set DocApp = GetObject(, "Word.Application")
If Err.Number = 429 Then
Err.Clear
Set DocApp = CreateObject("Word.Application")
End If
DocApp.Visible = True
'DocName = "C:UsersggujadhurDownloadsoutput.docx"
DocName = "C:Usersnicolas.jouffroyDownloadsoutput.docx"
If Dir(DocName) = "" Then
'MsgBox "File " & DocName & vbCrLf & "not found " & vbCrLf & "C:UsersggujadhurDownloads.", vbExclamation, "Document doesn't exist."
MsgBox "File " & DocName & vbCrLf & "not found " & vbCrLf & "C:Usersnicolas.jouffroyDownloads.", vbExclamation, "Document doesn't exist."
Exit Sub
End If
DocApp.Activate
Set DocFile = DocApp.Documents(DocName)
If DocFile Is Nothing Then Set DocFile = DocApp.Documents.Open(DocName)
DocFile.Activate
'Dim wordrange As Word.Range
'Set rng = wdDoc.Content
'word file part
For Each row In rng.Rows
For Each cell In row.Cells
cell.Copy
DocFile.Content.InsertAfter cell.Value
DocFile.Paragraphs.Last.Range.Style = wdStyleHeading1
DocFile.Content.InsertAfter vbCr
Next cell
Next row
'word file save etc.
DocFile.Save
'DocApp.Quit
Set DocFile = Nothing
Set DocApp = Nothing
Application.CutCopyMode = False
'word file save etc.
End Sub
The script works for the excel file parsing and pasting into the word file, but it does not format the pasted text to Heading1.
Any help would be greatly appreciated. Thank you!
Nicolas
PS: I tried re-writing the code to test formatting to Bold the last paragraph, and that works. I also tried to program a selection, then change the style to Heading 1.
Nicolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.