繁体   English   中英

VBA如何将格式文本从Excel传递到MS Word

[英]VBA How to pass formatted text from Excel to MS Word

我要求在哪里需要使用VBA在Excel中比较两个文本示例。 由于每个文本样本在LEN中都超过3000个字符,因此我使用Userform.TextBox字段提取,将它们存储为字符串变量。

接下来,我使用由“ mikerickson ”在这里找到的VBA代码:要编译VBA例程

比较文本。 问题是此代码的输出输入到单元格:A1中。 由于文本示例每个包含3000个以上的字符,因此由于excel对每个单元格的字符数有限制,因此结果不会显示在A1中。

我想知道如何将结果(带有下划线和删除线等所有格式)输入到MS Word文档中。

当前,这是用于输出到单元格A1的代码。

strResult = ComparedText(strOne, strTwo, olStart, olLength, nwStart, nwLength)

With outCell.Cells(1, 1)
    .Clear
    .Value = strResult
    For i = LBound(olStart) To UBound(olStart)
        If olStart(i) <> 0 Then

            With .Characters(olStart(i), olLength(i)).Font
                .ColorIndex = 3
                .StrikeThrough = True
            End With
        End If
    Next i
    For i = LBound(nwStart) To UBound(nwStart)
        If nwStart(i) <> 0 Then
            With .Characters(nwStart(i), nwLength(i)).Font
                .ColorIndex = 4
                .Underline = True
            End With
        End If
    Next i
End With

这里需要替换代码,该代码将把strResult输入到word文档中,其格式与上面的代码完全不匹配。

希望有人能帮上忙。 提前致谢。

这将从单元格A1到Word。 如果单元格A1中的数据被截断,那么我们将不得不更深入地研究。

Set wordy = CreateObject("Word.Application")

wordy.Documents.Add
Sheets(1).Range("A1").Copy
wordy.Documents(1).ActiveWindow.Selection.PasteSpecial DataType:=wdPasteRTF
wordy.Visible = True

'wordy.Quit

Set wordy = Nothing

如果我们可以将strResult插入Word并在那里进行格式化,那么这可能对您有用...

Set wordy = CreateObject("Word.Application")

wordy.Documents.Add
wordy.Documents(1).ActiveWindow.Selection.InsertAfter Text:=strResult
wordy.Documents(1).Range.Select
wordy.Visible = True

With wordy.Selection

For i = LBound(olStart) To UBound(olStart)
    If olStart(i) <> 0 Then

        For j = olStart(i) To (olStart(i) + olLength(i) - 1)
            With .Characters(j).Font
                .ColorIndex = 3
                .Strikethrough = True
            End With
        Next j
    End If
Next i

For i = LBound(nwStart) To UBound(nwStart)
    If nwStart(i) <> 0 Then
        For j = nwStart(i) To (nwStart(i) + nwLength(i) - 1)
            With .Characters(j).Font
                .ColorIndex = 4
                .Underline = True
            End With
        Next j
    End If
Next i
End With

Set wordy = Nothing

这可能不是最有效的代码,但是希望可以使您朝正确的方向前进。 我必须创建j循环,因为看起来在Word中, Characters对象一次只能访问一个字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM