【问题标题】:Create a new selection object at run time in word vba在运行时在 word vba 中创建一个新的选择对象
【发布时间】:2015-02-25 04:48:51
【问题描述】:
我之前问过这个问题,但我认为我不够清楚。
我需要编写一个 Word VBA 宏,它会在宏开始运行后通过突出显示来提示用户选择一些文本,然后处理新的选择。此过程将在宏内重复未知次数。
我遇到的唯一问题是弄清楚如何让 VBA 宏“暂停”并允许用户进行此选择。如果有人熟悉 AutoCAD VBA,我正在寻找与 AcadSelectionSet.SelectOnScreen 方法等效的方法。这看起来如此明显和根本,但我在 Microsoft 帮助文件或在线搜索中找不到任何告诉我如何执行此操作的内容。可以的话请帮忙!
【问题讨论】:
标签:
vba
ms-word
selection
【解决方案1】:
您是否应该查看Application 对象的WindowSelectionChange 事件?
在特殊的ThisDocument 模块中,您需要这样的代码:
Public WithEvents app As Application
Private Sub app_WindowSelectionChange(ByVal Sel As Selection)
MsgBox "The selection has changed"
End Sub
显然用有用的代码替换MsgBox 并使用Sel 参数访问选择。如果您想尝试其他活动,请使用ThisDocument 模块顶部的下拉菜单
要设置它,您需要在普通代码模块中使用这样的宏:
Sub setUpApp()
Set ThisDocument.app = ThisDocument.Application
End Sub
After setUpApp has run once, the app_WindowSelectionChange event will be triggered whenever the selection changes
【解决方案2】:
您可以使用无模式表单让您的宏继续运行,直到满足特定条件:
表单设计器:
表格代码:
Option Explicit
Dim m_stopHere As Boolean
Dim m_timesDone As Long
Private Sub CommandButton1_Click()
m_timesDone = m_timesDone + 1
m_stopHere = Not DoStuff(m_timesDone)
Me.Caption = "DoStuff was called " & m_timesDone & " time(s)."
If m_stopHere Then
MsgBox "Processing finished, closing form..."
Unload Me
End If
End Sub
Private Function DoStuff(times As Long) As Boolean
Dim myCondition As Boolean
If times < 5 Then
MsgBox "You selected: " & Selection.Text
Selection.Collapse wdCollapseEnd
myCondition = True
Else
Me.Label1.Caption = "No more selections, thanks!"
End If
DoStuff = myCondition
End Function
Private Sub UserForm_Initialize()
Me.Label1.Caption = "Please select some text in Word and press the button."
End Sub
另一个代码模块:
Sub StopAndGo()
UserForm1.Show vbModeless
End Sub