簡體   English   中英

excel vba:使字符串的一部分加粗

[英]excel vba: make part of string bold

我有包含如下條目的excel單元格:

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

單元格內容顯示在同一單元格的多行上。 我想為所有條目僅將“名稱”設為粗體。 我錄制了一個宏,我認為解決方案必須是這樣的:

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

我不知道的是如何獲取每個條目的起始值和長度。 有人有想法嗎?

立即擁有:

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

受到最近幾天各種研究的啟發:

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

這可能有點過頭了,但我已經對其進行了測試,它的作用就像一個魅力。 希望這可以幫助!

上面的答案完全沒問題。 由於它的相關性,我想包含一個類似的例程,我編寫的用於解決我妻子宏中的格式化問題。

在她的情況下,我們正在合並字符串並將串聯寫入由 vbCrLf (Chr(10)) 分隔的單個單元格,在她的最終輸出中它看起來像這樣

第 1 類:
類別#2:
第 3 類:

每個類別的長度是不同的,類別的數量可能從 1 個單元格到下一個單元格不等。 粘貼的子程序很好用

Sub BoldCategory() 
RowCount = ActiveSheet.UsedRange.Rows.Count
Set MyRange = ActiveSheet.Range(Cells(2, 1), Cells(RowCount, 1))
For Each Cell In MyRange
    i = 1
    LineBreak = 1
    Do While LineBreak <> 0
        EndBoldPoint = InStr(i, Cell.Value, ":") + 1
        BoldLength = EndBoldPoint - i
        Cell.Characters(Start:=i, Length:=BoldLength).Font.FontStyle = "Bold"
        LineBreak = InStr(i, Cell.Value, Chr(10))
        i = LineBreak + 1
    Loop
Next Cell
End Sub

所以“:”是我為了得到終點而鍵入的字符。 Chr(10) 告訴我 1 行何時結束,下一行何時開始。 當到達最后一行時,instr 返回 0,因此 while 循環退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM