繁体   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