2017-03-14 4 views
2

これらの値をA10、B10、C10、D10、E10、F10、G10、H10、I10、J1に変更することを目安にしてください。VBAを使用してセル内の文字列の一部のみをフォーマットする方法

たとえば、「Yonge St A10、B10」は、青いフォントの色にする必要がありますが、「Yonge St」は黒のままです。

私はVBAコードを持っています。ただし、コードはセル内のすべてのテキストの色を変更し、変更する必要がある特定のテキストは変更しません。以下を参照してください:

Dim i As Long 
Dim sequences As String 

' The sequence contains the values to highlight 
sequences = "A10,B10,C10,D10,E10,F10,G10,H10,I10,J1" 

' Split sequence list, so it can loop through each value in the array 

Dim seqList() As String 
seqList = Split(sequences, ",") 

' This loops through up to Row 20 to determine if the cell value contains a sequence value, if it does, then it highlights it blue 
For i = 1 To 20 
    Dim cellVal As String 
    cellVal = Cells(i, 2).Value 'Cells (i, 2) --> i refers to row number and 2 refers to column number. So in this case I set it to B 

    For Each seq In seqList 
     Dim outcomeNum As Integer 
     outcomeNum = InStr(cellVal, seq) 

     If outcomeNum > 0 Then 
      Cells(i, 2).Font.Color = RGB(0, 0, 255) ' You can set the blue colour here or change it to something else 
     End If 

     Next seq 

    Next i 
+0

[フレーズ内のキーワードの数とハイライト](http://stackoverflow.com/questions/32860792/count-and-highlight-keywords-within-phrases/32878493#32878493)を参照してください。 – Jeeped

答えて

2

あなたはフォーマットすることを、セル内の文字の開始と長さを指定する必要があります。

したがって

Cells(i, 2).Characters(Start:=outcomeNum, Length:=Len(seq)).Font.Color = RGB(0, 0, 255) 

Cells(i, 2).Font.Color = RGB(0, 0, 255) 

を置き換えます

ちょうど私が気づいた使用:宣言にseqがありません。

Dim seq As Variant 

私は、任意の宣言を忘れて、変数名にタイプミスによるエラーを最小限に防ぐためにOption Explicitを使用することをお勧めします。

+0

ありがとうございました!!!!できます – user35002

関連する問題