vba excel属性是否可以返回word.range?
我希望我的类属性返回word.range对象,然后将其插入word文档中。我希望它返回word.range而不是字符串的原因是我希望文本预先格式化,即文本的某些部分为粗体。以下是我尝试的代码:vba excel属性是否可以返回word.range?,excel,vba,ms-word,Excel,Vba,Ms Word,我希望我的类属性返回word.range对象,然后将其插入word文档中。我希望它返回word.range而不是字符串的原因是我希望文本预先格式化,即文本的某些部分为粗体。以下是我尝试的代码: Property Get wordRange() As word.Range Dim result As word.Range 'invalid use of new keyword Set result = New word.Range result.text = &q
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问题,因此我试图找到解决该问题的方法。如果您的类创建了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
您也不能新建Excel.Range;-您需要一个带有Word.Document的Word.Application实例来获取Word.Range,这类似于您需要一个Excel.Worksheet实例来从中提取Excel.Range。虽然此解决方案可行,但过于复杂。最简单的解决方案是将所需文本添加到目标文档中,并根据需要对其进行格式化。顺便说一句,解决方案中不需要使用剪贴板。最后两行可以替换为wrngTarget.FormattedText=wrngSource.FormattedText谢谢Timothy。我同意你的看法,那是不必要的复杂。我更新了有关FormattedText属性的解决方案。