Word中的VBA样式段落 [英] VBA Styling Paragraphs in Word

查看:87
本文介绍了Word中的VBA样式段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Excel文档格式化Word文档.我得到了

I am trying to format a Word Document from an Excel Document. I am getting

运行时错误5941:集合中所请求的成员没有存在.

Runtime Error 5941: The requested member of the collection does not exist.

我只是想将第二段样式设置为普通"内置样式.我缺乏经验可能表明.问题似乎出在段落选择上,但是我不完全确定该怎么做.

I am simply trying to style the second paragraph as the Normal built in style. My lack of experience probably shows. The problem seems to be with the paragraph selection, but I'm not entirely sure how to go about it.

Dim WordApp As Word.Application
Set WordApp = New Word.Application

WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
WordApp.Visible = True

WordApp.Selection.TypeText ("New Document")

WordApp.Selection.Paragraphs(1).Style = wdStyleHeading1

WordApp.Selection.TypeText vbNewLine & "Date" & Date

WordApp.Selection.Paragraphs(2).Style = wdStyleNormal

End Sub

我现在正在尝试寻找在同一行上更改格式的最佳方法.例如:

I am now trying to find the best way to change format on the same line. For Example:

日期: 2021年10月2日

Date: 10/02/2021

问题在于,到目前为止,我的样式更改已应用于整个段落.有什么想法吗?

The problem is that so far my style changes apply to a whole paragraph. Any ideas?

推荐答案

更好:

Sub Demo()
Dim WdApp As New Word.Application, WdDoc As Word.Document
With WdApp
  .Visible = True
  Set WdDoc = .Documents.Add
  With WdDoc
    .Range.Text = "New Document" & vbCr & "Date: " & Date
    .Paragraphs(1).Style = wdStyleHeading1
  End With
End With
End Sub

请注意,缺少用于选择普通"模板或将普通样式"应用于第二段的代码.那是因为默认模板是'Normal',默认样式是'Normal',因此指定那些不是普通的模板是没有必要的.如果您希望整个文档使用特定的默认样式,而仅用标题等替换,请通过'.Paragraphs(1).Style =' before '.Range.Text进行应用.='.

Note the absence of code to select the Normal template or to apply the Normal Style to the 2nd paragraph. That's because the default template is 'Normal' and the default Style is 'Normal', hence specifying those shouldn't ordinary be necessary. If you wanted a particular default Style for the document as a whole, only to be replaced by headings, etc., apply that via '.Paragraphs(1).Style = ' before '.Range.Text = '.

这篇关于Word中的VBA样式段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆