excel - 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
是否可以在“真空”中创建一个对象并返回它?如果是这样,它是否可以同时包含粗体和常规格式?
解决方案
首先@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
推荐阅读
- postgresql - 如何在覆盖“CREATE UNIQUE INDEX”约束时批量更新?
- node.js - 有没有办法使用类验证器实现文件上传验证?
- android - Android Grid Layout Cardview 项目仅在屏幕顶部可见
- jquery - 具有服务器端处理的 Datatable 的 Codeigniter 动态列
- html - 如何使用 CSS 在导航栏下添加阴影?
- javascript - 显示一个 div 并隐藏其余的 onclick
- java - 在服务中的每个方法调用之前运行注释处理器
- android - Android 如何实现 AsyncTask?EditText 没有响应的地方
- html - 使用时提交什么数据
- groovy - 加载 groovy 文件时捕获异常