在用户窗体中使用 Webbrowser 控件的可能解决方法
由于您的评论:“...实际上我正在使用 MSForms.TextBox”
一种可能的解决方法是使用 b 标记创建一个简单的 HTML 文件(例如,普通文本中的 blablabold text ...)用于粗体文本并加载将其放入 Webbrowser 控件(需要参考 Microsoft Internet Controls),例如通过 WebBrowser1.Navigate ThisWorkbook.Path & "\topic.htm"。
由于 HTML 通常使用 utf-8 编码,我演示了一种使用系统函数 WideCharToMultiByte(API 调用)的方法。
使用帮助函数的示例调用(API 调用)
' declare and assign simple html string
Dim htmlstring as String
htmlstring = "<html><body><div>Normal text <b>bold text</b> further text</div></body></html>"
' write html file via helper procedure
writeUtf8 htmlstring, ThisWorkbook.Path & "\topic.htm"
' load html file into WebBrowswer control
Me.WebBrowser1.Navigate ThisWorkbook.Path & "\topic.htm"
辅助程序
我建议为这些辅助函数编写一个单独的代码模块:
Option Explicit ' declaration head of separate code module
' Declare API Function
Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long, _
ByVal lpMultiByteStr As Long, _
ByVal cbMultiByte As Long, _
ByVal lpDefaultChar As Long, _
ByVal lpUsedDefaultChar As Long) As Long
Public Sub writeUtf8(ByVal s As String, ByVal datei As String)
' Purpose: save HTML String in utf-8 mode
' Note: called by writeUtf8 htmlstring, thisworkbook.path & "\topic.htm"
Dim file As Integer
Dim B() As Byte
file = FreeFile
Open datei For Binary Access Write Lock Read Write As #file
getUtf8 s, B
Put #file, , B
Close #file
End Sub
Private Sub getUtf8(ByRef s As String, ByRef B() As Byte)
' Note: called by above helper function; uses API call (see declaration head)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
Erase B
len_s = Len(s)
If len_s = 0 Then _
err.Raise 30030, , "Len(WideChars) = 0"
ptr_s = StrPtr(s)
size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
If size = 0 Then _
err.Raise 30030, , "WideCharToMultiByte() = 0"
ReDim B(0 To size - 1)
If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(B(0)), size, 0, 0) = 0 Then _
err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub