首页 > 解决方案 > vba excel属性是否可以返回word.range?

问题描述

我希望我的类属性返回word.range对象,然后将其插入到 word 文档中。我希望它返回word.range,而不是 astring的原因是因为我希望文本被预先格式化(即,文本的某些部分是粗体)。这是我尝试过的代码:

Property Get wordRange() As word.Range

    Dim result As word.Range
    'invalid use of new keyword
    Set result = New word.Range
    result.text = "the text here is bold"
    result.Bold = True
    wordRange = result
End Property 

word.range是否可以在“真空”中创建一个对象并返回它?如果是这样,它是否可以同时包含粗体和常规格式?

标签: excelvbams-word

解决方案


首先@Mathieu Guindon 是对的。我正在经历文字,所以我试图找到解决问题的方法。如果您的类创建了 Word.Application 和 Word.Document 的单独实例,则可以根据需要使用它。我添加了类初始化和终止,所以类(命名为 clsWrd)是:

Private wApp As Word.Application
Private wDoc As Word.Document

Property Get wordRange() As Word.Range
    Dim result As Word.Range
    Set result = wDoc.Paragraphs(1).Range
    result.Text = "the text here is bold"
    result.Bold = True
    Set wordRange = result
End Property

Private Sub Class_Initialize()
    Set wApp = New Word.Application
    'App.Visible = True
    Set wDoc = wApp.Documents.Add
End Sub

Private Sub Class_Terminate()
    wApp.Quit False
    Set wApp = Nothing
End Sub

这部分演示了它的使用

Sub test()
    'Create and initialize the class
    Dim nk As clsWrd
    Set nk = New clsWrd
    
    'Simulate/demostrate the main word application
    Dim wApp As Word.Application
    Dim wDoc As Word.Document
    Set wApp = New Word.Application
    wApp.Visible = True
    Set wDoc = wApp.Documents.Add
    Dim wrngTarget As Word.Range
    Set wrngTarget = wDoc.Paragraphs(1).Range
    
    'Use the object
    Dim wrngSource As Word.Range
    Set wrngSource = nk.wordRange
    'wrngSource.Copy
    'wrngTarget.Paste
    wrngTarget.FormattedText = wrngSource.FormattedText
End Sub

推荐阅读