2012-12-13 120 views
1

作爲Excel編程的新手,我在網上搜索了一個函數/ UDF/VBA,我可以在Excel中使用它來查找子字符串並將其加粗/顏色它在這個單元格中。在Excel單元格中查找和格式化子字符串

我在下面有這種表格。 - A列包含文本,以部分地格式化, - B列包含子串我尋找, - C列包含在字符串(A)中的子串(B)

  A   B   C 
1 ABCDEFGHIJKLM FGHI  6-9 
2 NOPQRSTUVWXYZ UVWXY  8-12 
... 
的位置

這裏我需要獲得:

  A   B   C 
1 ABCDE**FGHI**JKLM FGHI  6-9 
2 NOPQRST**UVWXY**Z UVWXY  8-12 
... 

是否有可能運用它整個列而不是隻有一行。

任何幫助或建議將不勝感激。 謝謝!

回答

1
' just add a loop and some checkings 
Sub t() 

Dim heightA As Long 
Dim heightB As Long 
Dim height As Long 
Dim i As Long 

heightA = Cells(Rows.Count, 1).End(xlUp).Row 
heightB = Cells(Rows.Count, 2).End(xlUp).Row 
If heightA < heightB Then 
    height = heightA 
Else 
    height = heightB 
End If 

If height > 1 Then 
    For i = 1 To height 
     Range("A" & i).Font.Bold = False 
     ''Replace the formula with the full string 
     Range("A" & i) = Range("A" & i).Value 
     'Find the starting position of the string in B within the string produced by the formula 
     If Range("B" & i).Value <> "" Then 
      myPos = InStr(1, Range("A" & i).Value, Range("B" & i).Value, 1) 
      If myPos > 0 Then 
       'Bold the string from B column 
       Range("A" & i).Characters(myPos, Len(Range("B" & i).Value)).Font.Bold = True 
      End If 
     End If 
    Next i 
End If 
End Sub 

EDIT:在格式 MASTER_STR使用位置時,SUBSTR1,POS1(START-END),SUBSTR2,POS2,e.t.c.

Sub t() 

Dim heightA As Long 
Dim heightB As Long 
Dim height As Long 
Dim i As Long 
Dim length As Long 
Dim tmp 
Dim width As Long 
heightA = Cells(Rows.Count, 1).End(xlUp).Row 
heightB = Cells(Rows.Count, 2).End(xlUp).Row 
If heightA < heightB Then 
    height = heightA 
Else 
    height = heightB 
End If 

If height > 1 Then 
    For i = 1 To height 
     Range("A" & i).Font.Bold = False 
     ''Replace the formula with the full string 
     Range("A" & i) = Range("A" & i).Value 
     'Find the starting position of the string in B within the string produced by the formula 
     width = Cells(i, Columns.Count).End(xlToLeft).Column 
     If width >= 3 Then 
      For j = 3 To width Step 2 
      If Cells(i, j).Value <> "" Then 
        tmp = Split(Cells(i, j).Value, "-") 
        myPos = CLng(tmp(0)) 
        length = CLng(tmp(1)) - myPos + 1 
        'myPos = InStr(1, Range("A" & i).Value, Range("B" & i).Value, 1) 
        If myPos > 0 Then 
         'Bold the string from B column 
         Range("A" & i).Characters(myPos, length).Font.Bold = True 
        End If 
       End If 
      Next j 
     End If 
    Next i 
End If 
End Sub 

樣例輸入

ABCDEFG A 1-1 C 3-5 
ABCDEFG A 1-1 C 3-3 
+0

真棒,這就是完美!非常感謝Larry! – lqdo

+0

如果您需要關於代碼的任何解釋,您可以評論/聊天我 – Larry

+0

我這麼認爲,但是如果列C,E ......以及之後已經給出了位置,那麼爲什麼我們需要列B,D .. – Larry

相關問題