Microsoft Word VBA-如果单元格包含指定的字符串,则选择表 [英] Microsoft Word VBA - Select table if cell contains specified string
问题描述
我在创建Microsoft-Word宏时遇到问题.这是我正在处理的宏.它可以成功选择Word文档中的每个表格.
I'm having trouble creating a Microsoft-Word macro. Here's the macro that I'm working on. It successfully selects each individual table in a word document.
Sub FindSpecificTables()
Selection.WholeStory
Dim iResponse As Integer
Dim tTable As Table
'If any tables exist, loop through each table in collection.
For Each tTable In ActiveDocument.Tables
tTable.Select
If response = vbNo Then Exit For 'User chose to leave search.
Next
MsgBox prompt:="Search Complete.", buttons:=vbInformation
End Sub
但是,如果表包含指定的字符串,则只需要选择一个表.这应该足够简单,但是我无法弄清楚.如何在表格中搜索特定字符串?
However, I only need to select a table if the table contains a specified string. This should be simple enough, but I can't figure it out. How can I search a table for a specific string?
我尝试使用以下条件语句来调整代码:
If tTable.Cell(1, 1) = "Adjusted:" Then tTable.Select
; 请参见下面的示例.
I've tried adjusting the code with the following conditional statement:
If tTable.Cell(1, 1) = "Adjusted:" Then tTable.Select
; see example below.
Sub FindSpecificTables()
Selection.WholeStory
Dim iResponse As Integer
Dim tTable As Table
'If any tables exist, loop through each table in collection.
For Each tTable In ActiveDocument.Tables
If tTable.Cell(1, 1) = "MySpecifiedString:" Then tTable.Select
If response = vbNo Then Exit For 'User chose to leave search.
Next
MsgBox prompt:="Search Complete.", buttons:=vbInformation
End Sub
不幸的是,这不起作用.我的语法错误吗?你们有什么建议吗?
Unfortunately, this isn't working. Is my syntax wrong? Do you guys have any suggestions or recommendations?
推荐答案
尝试使用其他方法...而不是循环每个表,请循环search (find)
方法,并检查找到的文本是否在表内.这是简单的解决方案:
Try with different approach... instead of looping each table loop search (find)
method and check if text found is within table. here is simple solution:
Sub Find_Text_in_table()
Selection.Find.ClearFormatting
With Selection.Find
.Text = "donec"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While Selection.Find.Execute
If Selection.Information(wdWithInTable) Then
Stop
'now you are in table with text you searched
'be careful with changing Selection Object
'do what you need here
End If
Loop
End Sub
这篇关于Microsoft Word VBA-如果单元格包含指定的字符串,则选择表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!