『セル内の特定文字に色付け』(DCM)
マクロの初心者です。
B列の各セルに複数の地名があります。
B3は横浜・神戸・札幌
B4は神戸・東京
・
・
・
B100は横浜・札幌・東京
横浜と東京のみを赤色に変更したいのですが、他の検索してみましたが
上手くいきませんでした。
ご教授よろしくお願いいたします。
< 使用 Excel:Excel2021、使用 OS:Windows11 >
Sub ColorYokohamaAndTokyo()
Dim rng As Range
Dim c As Range
Dim posYokohama As Long
Dim posTokyo As Long
Dim str As String
' B3からB100の範囲を指定
Set rng = Range("B3:B100")
For Each c In rng
str = c.Value
' 「横浜」の位置を検索
posYokohama = InStr(str, "横浜")
If posYokohama > 0 Then
' 「横浜」の文字色を赤に
c.Characters(Start:=posYokohama, Length:=Len("横浜")).Font.Color = RGB(255, 0, 0)
End If
' 「東京」の位置を検索
posTokyo = InStr(str, "東京")
If posTokyo > 0 Then
' 「東京」の文字色を赤に
c.Characters(Start:=posTokyo, Length:=Len("東京")).Font.Color = RGB(255, 0, 0)
End If
Next c
End Sub
(稚拙) 2025/11/18(火) 16:53:12
かぶったが。 これではどうだろうか? B3セルからB100セルまでを対象にしている。 また、同一セル内に東京、および横浜が複数ある場合も考慮している。
Sub test()
Dim RNG As Range
Dim POS As Integer
For Each RNG In Range("B3:B100")
POS = InStr(RNG.Value, "東京")
Do Until POS = 0
RNG.Characters(POS, 2).Font.ColorIndex = 3
POS = InStr(POS + 2, RNG.Value, "東京")
Loop
POS = InStr(RNG.Value, "横浜")
Do Until POS = 0
RNG.Characters(POS, 2).Font.ColorIndex = 3
POS = InStr(POS + 2, RNG.Value, "横浜")
Loop
Next
End Sub
(ねむねむ) 2025/11/18(火) 16:55:34
(そんな無茶な) 2025/11/18(火) 17:13:40
「*横浜*」の数が1以上のときに、背景を赤にする 「*東京*」の数が1以上のときに、背景を赤にする
って条件にすればいいとおもうのですが。
(もこな2) 2025/11/18(火) 18:36:54
やってることは同じですが、Findメソッドを使ってみました。
Sub main()
SetTextColor Range("B3:B100"), "東京", vbRed
SetTextColor Range("B3:B100"), "横浜", vbRed
End Sub
Sub SetTextColor(Rng As Range, str As String, Color As Long)
Dim fCell As Range, firstAddres As String
Set fCell = Rng.Find(What:=str, LookAt:=xlPart, MatchCase:=True, SearchFormat:=False)
If fCell Is Nothing Then Exit Sub
firstAddres = fCell.Address
Do
fCell.Characters(InStr(fCell.Value, str), Len(str)).Font.Color = Color
Set fCell = Rng.FindNext(after:=fCell)
Loop Until fCell.Address = firstAddres
End Sub
(´・ω・`) 2025/11/19(水) 16:58:33
こんな方法でも 1) Wordにコピペ 2)フォントを赤色に置換 E3)Excelにコピペ (マナ) 2025/11/19(水) 22:25:18
[ 一覧(最新更新順) ]
YukiWiki 1.6.7 Copyright (C) 2000,2001 by Hiroshi Yuki.
Modified by kazu.