如何将 Excel 范围文本格式化为 HTML

How to Format Excel Range text to HTML

我正在开发一个 VBA 函数,可以将特定 Excel 范围内的文本上传到服务器。由于我还在 Web 应用程序中显示服务器数据,因此我想保留源格式(即,如果 Excel 中的某些单词是粗体,我想保留它)。目前,我只关心粗体格式。我开发了以下解决方案,但它非常慢(转换带有多个句子的单个单元格可能需要约 2 分钟)。看看是否有更快的方法来实现这一目标。

Public Function getTextWithBold(rngText As Range) As String

    Dim currentIsBold As Boolean
    currentIsBold = False
    Dim returnValue As String
    returnValue = ""
    
    For i = 1 To Len(rngText.Value)
        If rngText.characters(i, 1).Font.Bold = True Then

            If currentIsBold = False Then
                currentIsBold = True
                returnValue = returnValue & "<b>" & rngText.characters(i, 1).Text
            Else
                returnValue = returnValue & rngText.characters(i, 1).Text
            End If

        Else

            If currentIsBold = True Then
                currentIsBold = False
                returnValue = returnValue & "</b>" & rngText.characters(i, 1).Text
            Else
                returnValue = returnValue & rngText.characters(i, 1).Text
            End If

        End If
        
        If ((rngText.characters(i, 1).Font.Bold = True) And (i = Len(rngText.Value))) Then
            returnValue = returnValue & "</b>"
        End If

   Next i

   getTextWithBold = returnValue

End Function

您想尽可能限制访问的次数Characters

应该更快:

Public Function getTextWithBold(rngText As Range) As String
    Dim isBold As Boolean, currBold As Boolean, i As Long
    Dim rv As String, txt As String
    txt = rngText.Value
    For i = 1 To Len(txt)
        isBold = rngText.Characters(i, 1).Font.Bold
        If isBold <> currBold Then
            rv = rv & IIf(currBold, "</b>", "<b>")
            currBold = isBold
        End If
        rv = rv & Mid(txt, i, 1)
    Next i
    getTextWithBold = IIf(currBold, "</b>", "") & rv
End Function

编辑:仅快 2-3 倍...