vba excel 属性是否可以返回 word.range?



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

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对象并将其返回?如果是这样,它是否可以同时包含粗体和常规格式?

首先@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

相关内容

最新更新