gpt4 book ai didi

vba - 使用 VBA,如何在 Excel 中的 Word 中编写不同标题级别的文本?

转载 作者:行者123 更新时间:2023-12-04 20:00:38 25 4
gpt4 key购买 nike

使用 VBA 2007,如何从 Excel 创建 Word 文档并编写不同标题(标题 1、标题 2、普通)的文本,以便标题出现在文档映射中?

最佳答案

此示例将从 Excel 运行。它使用早期绑定(bind),因此您需要确保在 VBA 引用(工具->引用)中设置了对 Word 的引用。

将文本放入文档中,Word 可能是一个善变的最佳选择。一般它需要去一个当前选择的点。您可以使用书签和/或域代码将文本放置在文档中的不同位置。

Sub MakeWordDocumentWithHeadings()

Dim wdApp As Word.Application, wdDoc As Word.Document

'Use on error resume next so VBA doesn't produce an error if it can't find Word Open
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")

'If it is nothing the open a new instance of word
If wdApp Is Nothing Then Set wdApp = New Word.Application
'Reset the errors
On Error GoTo 0

'Add a new document
Set wdDoc = wdApp.Documents.Add

'Word works by the location of the 'selection'
wdApp.Selection.Style = ActiveDocument.Styles("Heading 1")
wdApp.Selection.TypeText Text:="Heading One"
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 2")
wdApp.Selection.TypeText Text:="Heading Two"
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 3")
wdApp.Selection.TypeText Text:="Heading Three"
wdApp.Selection.TypeParagraph

'Save close or whatever here

'Always set objects to nothing.
Set wdDoc = Nothing
Set wdApp = Nothing

End Sub

关于vba - 使用 VBA,如何在 Excel 中的 Word 中编写不同标题级别的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12832289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com