【问题标题】:Convert RTF (Rich Text Format) code into plain text in Excel在 Excel 中将 RTF(富文本格式)代码转换为纯文本
【发布时间】:2017-03-03 10:22:23
【问题描述】:

我正在将数据库查询导出为 Excel,并且我正在获取具有 RTF 格式的行。

如何将这些字段转换为纯文本?我找到了很老的答案,所以我想知道是否有人知道方法。

【问题讨论】:

  • @Slai 这是我读到的第一个。它是旧的。我试过了,它不支持x64。从那以后的 8 年里,我希望有人找到更好的方法。另外,我不擅长 VBA。

标签: vba excel 64-bit rtf


【解决方案1】:

.Net Framework RichTextBox 类可以执行转换。幸运的是,这个类具有 ComVisibleAttribute 集,因此可以从 VBA 中轻松使用它。

我必须创建一个 .tlb 文件来引用。在

%SYSTEMROOT%\Microsoft.NET\Framework\currentver\

目录,运行命令

regasm /codebase system.windows.forms.dll

创建 system.windows.forms.tlb 文件。我的系统上已经有了这个 .tlb 文件,但是我必须使用这个命令重新创建它才能在 VBA 中成功创建一个 .Net System.Windows.Forms RichTextBox 对象。

创建新的 .tlb 文件后,在 VBA 中通过工具->VBA IDE 中的引用将其链接到您的项目。

我在 Access 中编写了这个测试代码来演示解决方案。

Dim rtfSample As String
rtfSample = "{\rtf1\ansi\deflang1033\ftnbj\uc1 {\fonttbl{\f0 \froman \fcharset0 Times New Roman;}{\f1 \fswiss \fcharset0 Segoe UI;}} {\colortbl ;\red255\green255\blue255 ;} {\stylesheet{\fs22\cf0\cb1 Normal;}{\cs1\cf0\cb1 Default Paragraph Font;}} \paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\headery720\footery720\deftab720\formshade\aendnotes\aftnnrlc\pgbrdrhead\pgbrdrfoot \sectd\pgwsxn12240\pghsxn15840\marglsxn1440\margrsxn1440\margtsxn1440\margbsxn1440\headery720\footery720\sbkpage\pgnstarts1\pgncont\pgndec \plain\plain\f1\fs22\lang1033\f1 hello question stem\plain\f1\fs22\par}"

Dim miracle As System_Windows_Forms.RichTextBox
Set miracle = New System_Windows_Forms.RichTextBox
With miracle
    .RTF = rtfSample 
    RTFExtractPlainText = .TEXT
End With

MsgBox RTFExtractPlainText(rtfSample)

结果

hello question stem

我假设在带有 64 位 Office 的 64 位 Windows 上需要在 \Framework64\ 目录中重新创建 .tlb 文件。我正在运行 64 位 Win10 和 32 位 Office 2013,所以我必须有一个 32 位 .tlb 文件。

【讨论】:

    【解决方案2】:

    另一种选择是使用 Microsoft 富文本框控件(但无法在 x64 Office 上进行测试)

    Sub rtfToText()
        With CreateObject("RICHTEXT.RichtextCtrl") ' or add reference to Microsoft Rich Textbox Control for early binding and With New RichTextLib.RichTextBox
            .SelStart = 0                          ' needs to be selected
            .TextRTF = Join(Application.Transpose(Cells.CurrentRegion.Columns(1)))
            [C1] = .Text                           ' set the destination cell here
    
            ' or if you want them in separate cells:
            a = Split(.Text, vbNewLine)
            Range("C3").Resize(UBound(a) + 1) = Application.Transpose(a)
        End With
    End Sub
    

    【讨论】:

    • 感谢您的回答。我一直在尝试运行它,但我一直收到错误消息ActiveX component can't create object。我已经允许宏了。
    • @Ivan 你可以从开发人员选项卡 > 插入 > 更多控件 > Microsoft 富文本框控件将控件添加到工作表吗?
    • 我无法在列表中找到控件。
    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多