簡體   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