메뉴
해결 엑셀2016

특정 색상의 텍스트를 다른 색상으로 일괄 변경하는 방법

프
10월 4일 조회 4,779
주어진 상황의 예시를 들자면 아래와 같습니다.

 



 

각 컬럼별 문자열 색상이 각각 달리 들어가 있어 Ctrl + H 를 통한 찾아 바꾸기 기능으로써 문자의 색상을 변경할 수는 없는 상태입니다. C와 D열은 마치 일괄적으로 변환이 가능한 것처럼 들어가 있으나 예시인 관계로 편의상 내용을 생략해 그렇고 실제로는 B열과 동일한 상황입니다.

 

현재 설정된 기존의 글자 색상을 기준으로 연녹색 → 진녹색, 하늘색 → 진청색 과 같은 형태로 기존 글자의 색상을 일괄적으로 변경하고자 합니다. 혹시 이를 수행 가능한 VBA 스크립트가 있을까요? 특정 문자열 내용을 기준으로 색상을 부여하는 기능은 많이 보이던데 이와 같은 상황에 대한 방안은 찾아봐도 없네요. 이렇게 작업해야 할 항목이 한두개면 직접 수정하고 끝내겠지만 이런 항목이 수백개에 달하는 상황이라 고수님들의 도움이 필요합니다.

댓글 10

엑
Sub FontColorPartOfText()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/vba-font-color-part/
     
    'Declare the following:
        'Step 1: Object variable to represent cell where you change the font color for part of the text
        'Variable to represent:
            'Step 2: Full text (with the substring whose font color you change)
            'Step 3: The text portion (substring) whose font color you change
            'Step 4: Number of characters in text portion (substring) whose font color you change
        'Step 2: Loop iteration variable
    Dim MyCell As Range
    Dim MyFullText As String
    Dim MyTextToChangeColor As String
    Dim MyTextToChangeColorLength As Long
    Dim iCounter As Long
     
    'Step 1: Assign object reference (to cell A6 in the "Excel VBA Font Color Part Text" worksheet in this workbook) to MyCell object variable
    Set MyCell = ThisWorkbook.Worksheets("Excel VBA Font Color Part Text").Range("A6")
     
    'Step 2: Assign string stored in cell represented by MyCell object variable to MyFullText variable
    MyFullText = MyCell.Value
     
    'Step 4: Assign string with text whose color you change to MyTextToChangeColor variable
    MyTextToChangeColor = "text"
     
    'Step 4: Assign number of characters in string represented by MyTextToChangeColor variable to MyTextToChangeColorLength variable
    MyTextToChangeColorLength = Len(MyTextToChangeColor)
     
    'Step 2: Loop from 1 to the number of characters in the string represented by MyFullText variable
    For iCounter = 1 To Len(MyFullText)
         
        'Do the following:
            'Step 4: Extract a helper string from the string represented by the MyFullText variable
                'Starting at the position equal to the current loop iteration
                'With a length equal to the number represented by the MyTextToChangeColorLength variable
            'Step 5: Test whether the helper string is equal to the string represented by the MyTextToChangeColor variable
            'Step 6: If the helper string is equal to the string represented by the MyTextToChangeColor variable, change the text portion (substring) whose font color you change
        If Mid(MyFullText, iCounter, MyTextToChangeColorLength) = MyTextToChangeColor Then
             
            'Step 7: Identify the part of text whose font color you change
            'Step 8: Use the RGB function to set the value of the Font.Color property. Specify the red, green, and blue components of the color as follows:
                'Red: 0
                'Green: 128
                'Blue: 55
            MyCell.Characters(iCounter, MyTextToChangeColorLength).Font.Color = RGB(0, 128, 55)
         
        End If
     
    Next iCounter
 
End Sub
Excel VBA Change Font Color for Part of Text in 8 Easy Steps (+ Example) (powerspreadsheets.com)

여기 참고해보세요~
프
프로스트 작성자 10월 7일
@엑셀킹이될꺼야 님 영어의 압박이... ㅎㅎ 지금까지 봐왔던 특정 문자열 내용을 기준으로 색상을 변환하는 예제로 보이는데 응용이 가능할 지 한번 찾아보겠습니다. 감사합니다~
원
원조백수 채택된 답변 10월 4일
Characters속성을 이용해서 아래와 같이 매크로 작성해 보세요.
실제 변경하려는 색을 Color1/2 -> 3/4에 반영해 주시면 됩니다.
Sub FontColorChange()
  Dim C As Range, iCnt As Long, i As Long
  Dim Color1 As Long, Color2 As Long, Color3 As Long, Color4 As Long
  
  Color1 = RGB(169, 208, 142): Color3 = RGB(0, 255, 0)  '// Color1 -> Color3 변경
  Color2 = RGB(155, 194, 230): Color4 = RGB(0, 0, 255)  '// Color2 -> Color4 변경
  
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  
  For Each C In ActiveSheet.UsedRange.Cells
    On Error Resume Next
    iCnt = 0
    iCnt = C.Characters.Count
    If iCnt > 0 Then
      For i = 1 To Len(C.Value2)
        Select Case C.Characters(i, 1).Font.Color
        Case Color1: C.Characters(i, 1).Font.Color = Color3
        Case Color2: C.Characters(i, 1).Font.Color = Color4
        Case Else
        End Select
      Next
    End If
  Next C

  Application.ScreenUpdating = True
  Application.EnableEvents = True
  MsgBox "완료되었습니다."

End Sub

 
프
프로스트 작성자 10월 7일
@원조백수 님 주신 예제 감사히 잘 받아봤습니다~ 셀 안에 들어간 색상 유형이 2가지로 모두 동일한 상황에서는 주신 내용대로 잘 변환이 됩니다만 셀 안에 색상이 제각각으로 들어간 경우 (2가지 색만 들어간 경우도 있고 어느 셀은 3가지 색도 들어가 있는 경우입니다) 에는 스크립트에 약간 변형을 주어야 하는 모양입니다. 변경하고자 했던 단일 색상 한 가지만 짚어서 변환하려고 했더니 엑셀이 무한 루프에 빠지네요. 이후는 제가 좀 더 알아보겠습니다. 감사합니다~
원
원조백수 10월 8일
@프로스트 님 잘 못 되더라도 무한루프에 빠지는 부분은 없는 것 같은데요...

색상수에 따라 Color1.2.3.4 부분이 있는 줄인 지정부분과 변경부분만 수정하면 됩니다.
프
프로스트 작성자 10월 8일
@원조백수 님 실제 작업할 파일에서 1줄만 남겨 다시 테스트 해보니 시간이 오래 걸려 엑셀이 응답 없음으로 표시되는 경우는 있습니다만 결국 기다리면 완료가 되네요. 변경하려는 색상만 지정해 작업 시도해보고 있습니다. 감사합니다~
프
프로스트 작성자 10월 8일
@원조백수 님 시트 전체를 두고 작업을 수행시키니 메모리 부족 오류가 뜨네요 ㅎㅎ 부분적으로 나누어 해야하나 봅니다. 주신 소스 감사히 쓰겠습니다~
프
프로스트 작성자 10월 9일
@원조백수 님 스크립트 적용 간 발생한 현상이 있어 몇 가지 문의 드립니다. 단일 색상 하나를 제외한 나머지 항목은 모두 주석처리 한 이후 색상을 변경할 시 상황이었습니다.
  1. 첫번째 항목은 맨 앞의 글자만 의도한 색상으로 변경되고 나머지 글자의 색상이 흑색으로 전환되었습니다.
  2. 화면에 표시된 색상과 해당 셀을 편집시 표시되는 색상이 다른 경우가 발생합니다.
  3. 모든 문자열이 강제 개행 되어있는 현상이 발생해 붙이려 하면 해당 문자열이 삭제되고 뒤쪽에 붙일 수 없는 현상이 발생합니다.


스크립트 적용 전과 후의 파일을 첨부해 드립니다. 혹시 해당 현상이 발생하는 원인을 알 수 있을까요?
원
원조백수 10월 9일
@프로스트 님 개별 Character별로 수정할 때 발생하는 문제인듯 합니다.
캐바캐라서 Excel의 bug인지도 모르겠습니다.

아래와 같이 개별이 아니라 연속된 글자색을 한 번에 변경하도록 모듈화 하여 호출하는 방식으로 변경해 봤습니다.
일단, 이렇게 적용할 경우 이상한 현상은 발생하지 않았습니다.
첨부 파일 참고하세요.
Sub CharacterFontColorChange(C As Range, FromC As Long, ToC As Long)
    Dim iCnt As Long, iPos As Long, iLen As Long, i As Long
    With C
      iCnt = 0
      iCnt = .Characters.Count
      If iCnt > 0 Then
        
        iPos = 0: iLen = 0: i = 0
        Do While True
          i = i + 1
          If i > iCnt Then Exit Do
          If .Characters(i, 1).Font.Color = FromC Then
              If iPos = 0 Then iPos = i: iLen = iLen + 1 Else iLen = iLen + 1
          Else
              If iPos > 0 Then .Characters(iPos, iLen).Font.Color = ToC: iPos = 0: iLen = 0
          End If
        Loop
      End If
    End With
End Sub

 
프
프로스트 작성자 10월 16일
@원조백수 님 수정해주신 코드 잘 받아서 사용했습니다~ 첫 문자열 속성의 색상을 변경하는 과정에서 볼드체가 해제되는 이슈는 있었지만 그래도 덕분에 엄청 시간을 절약했습니다. 감사합니다~

질문답변 게시판의 최근 글

로그인

처음이면 카카오·네이버로 계속하면 바로 가입돼요

또는
비밀번호 찾기
Caps Lock이 켜져 있습니다
스크랩 완료