我正在编写一个宏,它将读取 Excel 表格并将表格中的值写入 Excel 文件。我希望宏获取 A 列中的值并将其格式化为 Heading1 样式,并获取 B 列中的值并将其格式化为 Heading2 样式,最后 C 列中的值应该只是普通样式。
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:\Users\ggujadhur\Downloads\output.docx"
DocName = "C:\Users\nicolas.jouffroy\Downloads\output.docx"
If Dir(DocName) = "" Then
'MsgBox "File " & DocName & vbCrLf & "not found " & vbCrLf & "C:\Users\ggujadhur\Downloads\.", vbExclamation, "Document doesn't exist."
MsgBox "File " & DocName & vbCrLf & "not found " & vbCrLf & "C:\Users\nicolas.jouffroy\Downloads\.", 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
该脚本适用于 Excel 文件解析并粘贴到 Word 文件中,但它不会将粘贴的文本格式化为 Heading1。
任何帮助将不胜感激。谢谢!
尼古拉斯
PS:我尝试重新编写代码来测试最后一段的格式为粗体,效果很好。我还尝试编写一个选择,然后将样式更改为标题 1。
您的代码失败,因为您正在使用后期绑定。这是一个不明智的选择,因为这样做没有任何好处,反而有很多缺点,比如这里的一个。
wdStyleHeading1
是一个 Word 常量。 Excel 不知道它的含义。
现在,您可以简单地在代码中提供该常量的值,或者您可以做出明智的选择并添加对 Word 的引用(工具 | 引用)并将变量正确声明为 Word 对象。