String VBA在文档中搜索字符串并检查其颜色
我尝试创建一个函数来搜索文档中的字符串,并检查红色字符串中的第一个字符是什么 例如,我知道我的文档包含字符串“面包水果汁桃子酒”。假设粗体文本为红色。我希望函数返回int 19(第一个红色字符-p) 每次尝试调用该函数时,都会出现错误“运行时错误424-需要对象” 我添加了一些MsgBox来查看函数何时中断,并在该位置添加了注释String VBA在文档中搜索字符串并检查其颜色,string,vba,search,colors,ms-word,String,Vba,Search,Colors,Ms Word,我尝试创建一个函数来搜索文档中的字符串,并检查红色字符串中的第一个字符是什么 例如,我知道我的文档包含字符串“面包水果汁桃子酒”。假设粗体文本为红色。我希望函数返回int 19(第一个红色字符-p) 每次尝试调用该函数时,都会出现错误“运行时错误424-需要对象” 我添加了一些MsgBox来查看函数何时中断,并在该位置添加了注释 有什么问题?如何修复它?第一件事:在模块开头使用选项Explicit。您很快就会发现代码存在编译问题 您的意思是使用oRng还是myRange?这应该是一致的 一旦你做
有什么问题?如何修复它?第一件事:在模块开头使用
选项Explicit
。您很快就会发现代码存在编译问题
您的意思是使用oRng
还是myRange
?这应该是一致的
一旦你做到了
Mid(myRange,i,1)
返回字符串,而不是对象
您可能希望使用如果包含字符(1).Font.Color=wdColorRed,则使用
以下是正确返回的已修改代码:
Function check(stringToCheck As String) As Integer
Dim oRng As Word.Range
Set oRng = ActiveDocument.Content
Dim i As Integer
With oRng.Find
' to ensure that unwanted formats aren't included as criteria
.ClearFormatting
'You don't care what the text is
.Text = stringToCheck
'Loop for each match and set a color
While .Execute
MsgBox (oRng.Text)
For i = 1 To 40
'take the Nth char of the string an check if it's red
'the following msgBox is working
MsgBox oRng.Characters(i)
If oRng.Characters(i).Font.Color = wdColorRed Then
'the following msgBox is not working which means the error is in the last line.
MsgBox ("made it")
check = i
Exit Function
End If
Next i
Wend
End With
End Function
@阿莫斯,我已经完成了我的回答。Range
对象有一个Characters
属性,可以让您随心所欲。哇,谢谢!但我认为你指的是人物(我),而不是人物(1)。@Amos啊,是的,对不起。此外,您可能需要考虑将循环从<代码> 1到40 <代码>调整为<代码> 1到Len(字符)< /代码>。
Function check(stringToCheck As String) As Integer
Dim oRng As Word.Range
Set oRng = ActiveDocument.Content
Dim i As Integer
With oRng.Find
' to ensure that unwanted formats aren't included as criteria
.ClearFormatting
'You don't care what the text is
.Text = stringToCheck
'Loop for each match and set a color
While .Execute
MsgBox (oRng.Text)
For i = 1 To 40
'take the Nth char of the string an check if it's red
'the following msgBox is working
MsgBox oRng.Characters(i)
If oRng.Characters(i).Font.Color = wdColorRed Then
'the following msgBox is not working which means the error is in the last line.
MsgBox ("made it")
check = i
Exit Function
End If
Next i
Wend
End With
End Function