【发布时间】:2017-03-03 10:22:23
【问题描述】:
【问题讨论】:
-
@Slai 这是我读到的第一个。它是旧的。我试过了,它不支持x64。从那以后的 8 年里,我希望有人找到更好的方法。另外,我不擅长 VBA。
【问题讨论】:
.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)
结果
我假设在带有 64 位 Office 的 64 位 Windows 上需要在 \Framework64\ 目录中重新创建 .tlb 文件。我正在运行 64 位 Win10 和 32 位 Office 2013,所以我必须有一个 32 位 .tlb 文件。
【讨论】:
另一种选择是使用 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。我已经允许宏了。