gpt4 book ai didi

excel - 更改excel单元格中文本的颜色

转载 作者:行者123 更新时间:2023-12-04 21:19:57 26 4
gpt4 key购买 nike

我想更改 MS Excel 中单元格中文本的颜色,例如条件格式。我在一个单元格中有不同的文本,例如“WUG-FGT”或“INZL-DRE”。我想格式化单元格(我的工作表中的所有单元格),定义的文本(如“WUG-FGT”)显示为红色,其他文本“INZL-DRE”显示为绿色,但文本位于同一单元格中。使用“标准”条件格式,我只能将背景着色。

一个类似的问题是:How can I change color of text in a cell of MS Excel?

但不同之处在于我(实际上)不从事编程工作。这意味着我需要一个更简单或更容易的解决方案来在我的 excel 文件中实现它。

这可能吗?使用 VBA 的解决方案也是可能的,我知道如何实现它们。

最佳答案

这里的示例如何实现所需的结果:

Sub test()
Dim cl As Range
Dim sVar1$, sVar2$, pos%
sVar1 = "WUG-FGT"
sVar2 = "INZL-DRE"
For Each cl In Selection
If cl.Value2 Like "*" & sVar1 & "*" Then
pos = InStr(1, cl.Value2, sVar1, vbTextCompare)
cl.Characters(pos, Len(sVar1)).Font.Color = vbRed
End If
If cl.Value2 Like "*" & sVar2 & "*" Then
pos = InStr(1, cl.Value2, sVar2, vbTextCompare)
cl.Characters(pos, Len(sVar2)).Font.Color = vbGreen
End If
Next cl
End Sub

测试

enter image description here

更新

Is it possible to count how often the word has been detected. Either to write to total amount to a defined cell or what also would be great, to add the number of counts in brackets behind the word with an control variable? So in your example: A2: "WUG-FGT(1)", A4: "WUG-FGT(2)", A5: "WUG-FGT(3)"



是的,但是您应该在着色之前更新单元格,否则整个单元格字体将由第一个字符的颜色着色(例如,单元格包含关键字并且第一个是红色,第二个是绿色,更新后整个单元格字体将是红色)。请参阅下面的更新代码和测试:
Sub test_upd()
Dim cl As Range, sVar1$, sVar2$, pos%, cnt1%, cnt2%
Dim bVar1 As Boolean, bVar2 As Boolean

sVar1 = "WUG-FGT": cnt1 = 0
sVar2 = "INZL-DRE": cnt2 = 0

For Each cl In Selection
'string value should be updated before colorize
If cl.Value2 Like "*" & sVar1 & "*" Then
bVar1 = True
cnt1 = cnt1 + 1
cl.Value2 = Replace(cl.Value, sVar1, sVar1 & "(" & cnt1 & ")")
End If

If cl.Value2 Like "*" & sVar2 & "*" Then
bVar2 = True
cnt2 = cnt2 + 1
cl.Value2 = Replace(cl.Value, sVar2, sVar2 & "(" & cnt2 & ")")
End If

pos = InStr(1, cl.Value2, sVar1, vbTextCompare)
If bVar1 Then cl.Characters(pos, Len(sVar1)).Font.Color = vbRed
pos = InStr(1, cl.Value2, sVar2, vbTextCompare)
If bVar2 Then cl.Characters(pos, Len(sVar2)).Font.Color = vbGreen

bVar1 = False: bVar2 = False
Next cl
End Sub

测试

enter image description here

关于excel - 更改excel单元格中文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com