一段落Word VBA中具有不同样式的文本 [英] Text with different styles in one paragraph Word VBA

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

问题描述

我想在一行中使用粗体而不是粗体文本.

    With objWrdDoc
        .Styles.Add ("S2")
        .Styles.Add ("S3")
        .Styles("S2").Font.Bold = True
        .Styles("S3").Font.Bold = False
    End With
    With objWrdApp.Selection
        .TypeParagraph
        .Style = objWrdDoc.Styles("S2")
        .TypeText Text:="I want to have bold "
        .Style = objWrdDoc.Styles("S3")
        .TypeText Text:="and not bold text in one line."
    End With

结果,整个文本不是加粗的.

As a result, the entire text is not bold.

推荐答案

虽然使用Selection对象感觉直观",但是编写代码来操纵Word的准确性不如使用Range对象.您可以将Range视为不可见的选择,其重要区别在于

While working with the Selection object feels "intuitive", it's not as accurate for writing code to manipulate Word as using Range objects. You can think about a Range as being an invisible selection, with the important differences that

  • 代码可以与多个Range对象一起使用
  • 用户无法影响Range的位置(单击屏幕或按箭头键会更改Selection)
  • 跟踪Range在代码中任意给定点的位置是可靠的
  • code can work with multiple Range objects
  • the user can't affect where a Range is (clicking on the screen or pressing arrow keys changes a Selection)
  • tracking where a Range is at any given point in the code is reliable

更改问题中的代码以使用目标" Range可能如下所示.

Changing the code in the question to work with a "target" Range could look as follows.

(请注意,我还为要定义的样式添加了Style对象.与对象(而不是诸如objWrdDoc.Styles("S3")之类的结构)一起使用时,它更可靠并且键入的次数更少.)

(Note that I've also added Style objects for the styles being defined. It's much more reliable and a lot less typing to work with objects, rather than constructs such as objWrdDoc.Styles("S3").)

   Dim S2 as Word.Style, S3 as Word.Style 'As Object if using late-binding
   With objWrdDoc
        Set S2 = .Styles.Add("S2")
        Set S3 = .Styles.Add("S3")
        S2.Font.Bold = True
        S3.Font.Bold = False
    End With

    Dim objRange as Word.Range 'As Object if using late-binding
    Set objRange = objWrdApp.Selection.Range

    With objRange
        .Text = vbCr 'Chr(13) = paragraph mark
        'The new text should follow the inserted paragraph mark
        'Like pressing right-arrow to "collapse" a selection
        .Collapse wdCollapseEnd

        'When working with ranges, apply the formatting after writing the text
        .Text = "I want to have bold "
        .Style = S2

        .Collapse wdCollapseEnd
        .Text = "and not bold text in one line."
        .Style = S3
    End With

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

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