Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel/VBA计算字符串中粗体字的数量_Vba_Excel_Count - Fatal编程技术网

Excel/VBA计算字符串中粗体字的数量

Excel/VBA计算字符串中粗体字的数量,vba,excel,count,Vba,Excel,Count,从昨天开始,我拼命想数一数一间牢房里有多少粗体字 像“foofoofoo”这样的词应该给出1,“foofoo-foo”应该给出2 这是我的最佳尝试,但它返回错误或#值: Function CountBold(工作范围) 变暗Rng As范围 暗X等于长 作为整数的Dim i Dim j尽可能长 Dim arText()作为变量 Rng=工作Rng.单元格(1,1).值 arText=拆分(Rng.Value,“”) 对于i=LBound(arText)到UBound(arText) j=仪表(0

从昨天开始,我拼命想数一数一间牢房里有多少粗体字

像“foofoofoo”这样的词应该给出1,“foofoo-foo”应该给出2

这是我的最佳尝试,但它返回错误或#值:

Function CountBold(工作范围)
变暗Rng As范围
暗X等于长
作为整数的Dim i
Dim j尽可能长
Dim arText()作为变量
Rng=工作Rng.单元格(1,1).值
arText=拆分(Rng.Value,“”)
对于i=LBound(arText)到UBound(arText)
j=仪表(0,参考值,参数(i),1)
如果j 0,则如果Rng.字符(j,Len(arText(i)).Font.Bold,则xCount=xCount+1
接下来我
CountBold=xCount
端函数
非常感谢您的帮助! 提前谢谢你! 弗朗西斯科

更新 下面的函数使用正则表达式

Function CountBold(WorkRng As Range) As Long
    Dim Rng As Range
    Dim sPattern As String
    Dim oRegExp As Object
    Dim oMatches As Object
    Dim oMatch As Object
    Dim Counter As Long

    Set Rng = WorkRng.Cells(1, 1)

    sPattern = "\w+" 'stands for at least one alphanumeric character or '_' character

    Set oRegExp = CreateObject("VBScript.RegExp")
    With oRegExp
        .Pattern = sPattern
        .Global = True
        Set oMatches = .Execute(Rng)
        For Each oMatch In oMatches
            If Rng.Characters(oMatch.FirstIndex + 1, oMatch.Length).Font.Bold Then Counter = Counter + 1
        Next
    End With

    CountBold = Counter
End Function
试试这个:

Function CountBold(WorkRng As Range)

    Dim i, xcount As Integer
    For i = 1 To Len(WorkRng)

    If WorkRng.Characters(i, 1).Font.Bold = True Then
        xcount = xcount + 1
    End If

Next i

CountBold = xcount
End Function

有可能有这样的字符串:“foo foo foo”(中间
o
为粗体)。如果是的话,答案应该是-0还是1?0-我只需要用粗体字计算整个单词。(提前感谢)不为字符串“abc**def**def”(注意,第一个和第二个def之间有4个空格)-返回2,但应返回1谢谢你!它起作用了!我想给你一个“放弃”,但我的名声不允许我……)再次感谢对于simoco,我删除了文本中的所有双空格。。。但你是对的,多个空格给出了不确定的行为。如果有一个单词后跟标点符号(如home。)Kapol,那么你的代码不计算它/
Function CountBold(WorkRng As Range)

    Dim i, xcount As Integer
    For i = 1 To Len(WorkRng)

    If WorkRng.Characters(i, 1).Font.Bold = True Then
        xcount = xcount + 1
    End If

Next i

CountBold = xcount
End Function