I'm trying to write a code to transfer an Excel file to Word with proper formatting, but when I set the format for one row, it gets applied to the next row instead.
Sub ExportToWordModifiedExcelData()
Dim wdApp As Object
Dim wdDoc As Object
Dim i As Integer
Dim colA As String, colB As String, colC As String, colD As String
Dim cycleCount As Integer
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdDoc = wdApp.Documents.Add
wdApp.Visible = True
header1 = "IV. 31. b."
header2 = "Forensic and criminal records"
header3 = "(Acta sedrialia et criminalia)"
cycleCount = 0
Const wdPageBreak = 1
For i = 1 To Cells(Rows.Count, 1).End(xlUp).Row
colA = Cells(i, 1).Value
colB = Cells(i, 2).Value
colC = Cells(i, 3).Value
colD = Cells(i, 4).Value
If cycleCount = 3 Then
wdDoc.Paragraphs.Last.Range.InsertBreak wdPageBreak
cycleCount = 0
End If
With wdDoc.Content
.InsertAfter header1 & vbCrLf
With wdDoc.Paragraphs.Last.Range
.Font.Size = 18
.Font.Bold = True
.ParagraphFormat.Alignment = 1
End With
End With
With wdDoc.Content
.InsertAfter header2 & vbCrLf
With wdDoc.Paragraphs.Last.Range
.Font.Size = 16
.Font.Bold = False
.ParagraphFormat.Alignment = 1
End With
End With
With wdDoc.Content
.InsertAfter header3 & vbCrLf
With wdDoc.Paragraphs.Last.Range
.Font.Size = 14
.Font.Bold = True
.ParagraphFormat.Alignment = 1
End With
End With
wdDoc.Content.InsertAfter vbCrLf
With wdDoc.Content
.InsertAfter colB & vbCrLf
With wdDoc.Paragraphs.Last.Range
.Font.Size = 16
.Font.Bold = True
.ParagraphFormat.Alignment = 1
End With
End With
With wdDoc.Content
.InsertAfter colC & " " & colD & vbCrLf
With wdDoc.Paragraphs.Last.Range
.Font.Size = 26
.Font.Bold = True
.ParagraphFormat.Alignment = 2
End With
End With
With wdDoc.Content
.InsertAfter colA & vbCrLf
With wdDoc.Paragraphs.Last.Range
.Font.Size = 16
.Font.Bold = True
.ParagraphFormat.Alignment = 1
End With
End With
If cycleCount < 2 Then
wdDoc.Content.InsertAfter vbCrLf
End If
cycleCount = cycleCount + 1
Next i
End Sub
With the current code, I get the expected result, but it's quite frustrating, so it should be that header1 has Font.size=16 and Font.Bold=True, header2 Font.size=18 and Font.Bold=True, header3 Font.size=16 and Font.Bold=False, etc.
wdDoc.Paragraphs.Lastis the new paragraph after the newline. Don't use newlines to control paragraphs. Word isn't a text editor. Create the Paragraph objects explicitly withParagraphs.Addinstead. Besides, shouldn't you be using a Table instead of adding a new paragraph for every Excel row?wdAlignTabDecimalis probably the best option if you want to display decimal values