2012-04-24 93 views
6

tôi có các tế bào excel có chứa các mục như thế này:Excel VBA: làm cho một phần của chuỗi đậm

name/A/date 
name/B/date 
name/C/date 

nội dung di động sẽ được hiển thị trên nhiều dòng trong cùng một tế bào. Tôi chỉ muốn tạo "tên" đậm cho tất cả các mục nhập. Tôi đã ghi lại macro và tôi nghĩ giải pháp phải giống như sau:

ActiveCell.FormulaR1C1 = "name/A/date" & Chr(10) & "name/B/date" & Chr(10) & "name/C/date" 
With ActiveCell.Characters(Start:=25, Length:=4).Font 
    .FontStyle = "Bold" 
End With 

Điều tôi không biết là làm cách nào để có được giá trị bắt đầu và độ dài của mỗi mục nhập. Bất cứ ai có một ý tưởng?

+0

bản sao có thể có của [Excel VBA: Thay đổi màu của các ký tự nhất định trong một ô] (http://stackoverflow.com/questions/7618121/excel-vba-change-color-of-certain-characters-in-a- ô) – brettdj

Trả lời

9

Có ngay:

lngPos = InStr(ActiveCell.Value, "/") 
With ActiveCell.Characters(Start:=1, Length:=lngPos - 1).Font 
    .FontStyle = "Bold" 
End With 
0

Lấy cảm hứng từ nghiên cứu khác nhau trong vài ngày qua:

Dim totalVals, startPos(), endPos(), i, j, strLen As Long 
Dim currLine As String 

' Split the cell value (a string) in lines of text 
splitVals = Split(ActiveCell.Value, Chr(10)) 

' This is how many lines you have 
totalVals = UBound(splitVals) 

' For each line, you'll have a character where you want the string to start being BOLD 
ReDim startPos(0 To totalVals) 

' And one character where you'll want it to stop 
ReDim endPos(0 To totalVals) 

' The value of the current line (before we loop on ActiveCell.Value) is empty 
currLine = "" 

For i = 0 To totalVals ' For each line... 

    ' Length of the string currently treated by our code : 0 if no treatment yet... 
    strLen = Len(currLine) 

    ' Here we parse and rewrite the current ActiveCell.Value, line by line, in a string 
    currLine = currLine & IIf(currLine = "", "", Chr(10)) & splitVals(i) 

    ' At each step (= each line), we define the start position of the bold part 
    ' Here, it is the 1st character of the new line, i.e. strLen + 1 
    startPos(i) = strLen + 1 

    ' At each step (= each line), we define the end position of the bold part 
    ' Here, it is just before the 1st "/" in the current line (hence we start from strLen) 
    endPos(i) = InStr(IIf(strLen = 0, 1, strLen), currLine, "/") 

Next i 

' Then we use the calculated positions to get the characters in bold 
For j = 0 To UBound(startPos) 
    ActiveCell.Characters(startPos(j), endPos(j) - startPos(j)).Font.FontStyle = "Bold" 
Next j 

Nó có thể là một chút quá trớn, buti đã thử nghiệm nó và nó hoạt động như một nét duyên dáng. Hi vọng điêu nay co ich!

Các vấn đề liên quan