VBA 查找字符串的字体颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26949079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA to find the font color of a string
提问by user3196470
I am new to VBA..I am writing a macro for some file comparison..My requirement is if a string has red color font,that string should be ignored for iteration and code should move to next iteration..I have tried the following code.
我是 VBA 新手。代码。
Dim compare = {"test1","test2","test3",.....etc}
i=0
For j=1 to Ubound(compare)
j=1
If compare.Characters(j,Len(compare(i))).Font.Color <> vbRed Then
' Some Code
End If
i=i+1
Next
However during the execution I am getting runtime error 424 "Object Required.Please help me to complete this task
但是在执行过程中,我收到运行时错误 424“Object Required. Please help me to complete this task
Thanks in advance.
提前致谢。
回答by Gary's Student
Say we have cells A1thru A4like:
假设我们有单元格A1到A4,例如:
Then this code will find the non-red characters:
然后这段代码会找到非红色字符:
Sub ColorTest()
Dim I As Long, J As Long
For I = 1 To 4
For J = 1 To Len(Cells(I, 1).Value)
If Cells(I, 1).Characters(Start:=J, Length:=1).Font.Color <> vbRed Then
MsgBox "non-red found at cell A" & I & " position " & J
End If
Next J
Next I
End Sub
回答by jemmy
May I assume that the source for your data is an excel-sheet (as pointed out by previous comments, a pure string does not hold information on colours), and for one reason or another you want to use an array. Then this might be a way to solve the problem (prerequisite: full string is in one colour only)
我是否可以假设您的数据源是一个 excel 表(正如之前的评论所指出的,纯字符串不包含颜色信息),并且出于某种原因您想要使用数组。那么这可能是解决问题的一种方法(前提条件:完整字符串只有一种颜色)
(Just saw that there's a solution provided by Gary's student without using arrays as well...AND providing for cases where only part of the string is red...nice one!)
(刚刚看到 Gary 的学生提供了一个解决方案,也没有使用数组......并且提供只有部分字符串是红色的情况......很好!)
Sub colour()
Dim arr_DB As Variant
Dim i As Long
ReDim arr_DB(1, 1) 'Array size to be adjusted as needed, Base 0 !
For i = 1 To 2
arr_DB(i - 1, 0) = ActiveSheet.Cells(i, 1).Value 'Value of Cell
arr_DB(i - 1, 1) = ActiveSheet.Cells(i, 1).Font.Color 'Colour of Font in Cell
Next
If arr_DB(i - 1, 1) = 255 Then ' No. 255 is colour RED
'skip.....
End If
End Sub