Excel在文本中提取粗体字
有人能帮我解决Excel问题吗? 我有一个充满文本的单元格。这篇课文的一些字用粗体印刷。这些单词是关键字,应该扩展到行中的另一个单元格以识别关键字。 例如: 单元格中的文本: 我想使用谷歌地图获取路线信息 输出: 谷歌;地图;路线 提前谢谢你 试试这个Excel在文本中提取粗体字,excel,vba,filter,Excel,Vba,Filter,有人能帮我解决Excel问题吗? 我有一个充满文本的单元格。这篇课文的一些字用粗体印刷。这些单词是关键字,应该扩展到行中的另一个单元格以识别关键字。 例如: 单元格中的文本: 我想使用谷歌地图获取路线信息 输出: 谷歌;地图;路线 提前谢谢你 试试这个 Option Explicit Sub Demo() Dim ws As Worksheet Dim str As String, strBold As String Dim isBold As Boolean
Option Explicit
Sub Demo()
Dim ws As Worksheet
Dim str As String, strBold As String
Dim isBold As Boolean
Dim cel As Range
Dim lastRow As Long, i As Long
Set ws = ThisWorkbook.Sheets("Sheet1") 'change Sheet1 to your data sheet
isBold = False
With ws
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row with data in Column A
For Each cel In .Range("A1:A" & lastRow).Cells 'loop through each cell in Column A
strBold = ""
For i = 1 To Len(cel.Value)
If cel.Characters(Start:=i, Length:=1).Font.Bold = True Then 'check if character is bold
isBold = True
str = Mid(cel.Value, i, 1)
If cel.Characters(Start:=i, Length:=1).Text = " " Then 'check for space
strBold = strBold & "; "
isBold = False
Else
strBold = strBold & str
End If
Else
If isBold Then
strBold = strBold & "; "
isBold = False
End If
End If
Next
cel.Offset(0, 1) = strBold
Next
End With
End Sub
从导出此代码。您也可以使用此UDF生成相同的结果。请在模块中输入以下代码
Public Function findAllBold(ByVal rngText As Range) As String
Dim theCell As Range
Set theCell = rngText.Cells(1, 1)
For i = 1 To Len(theCell.Value)
If theCell.Characters(i, 1).Font.Bold = True Then
If theCell.Characters(i + 1, 1).Text = " " Then
theChar = theCell.Characters(i, 1).Text & ", "
Else
theChar = theCell.Characters(i, 1).Text
End If
Results = Results & theChar
End If
Next i
findAllBold = Results
End Function
现在您可以使用新创建的函数从任何单元格返回粗体值
@NikolaosPolygenis-您是否尝试执行上述代码?是的,工作正常(使用.Font.Bold=True)。使用Font.FontStyle=“Bold”的前一个代码在cel.Offset(0,1)中不传递文本。@NikolaosPolygenis-我在发布之前测试了代码,即使使用
Font.FontStyle=“Bold”也可以正常工作
尽管使用.Font.Bold=True
更好。第二,可以在同一行中声明多个变量,用,
分隔,所以变量的声明没有错,试试看。对于您正确的声明,在我的评论中,我写下您不能声明ex:dim str,strbold为string,但您将dim str作为string,strbold作为字符串被接受…我很抱歉。@NikolaosPolygenis-显然使用.Font.Bold=True更好,顺便说一句,很高兴找到它不起作用的原因。非常感谢您使用这个宏。也很有魅力:-)