将文本从 Word 复制到 Excel,同时保持格式使用 .typetext

问题描述

我正在尝试将 Excel 电子表格中的问题和回复数据复制到 Word 文档中。我有一个宏,它可以通过使用 .typetext 指令来显示所有文本 - 这会导致上标和下标文本作为标准文本出现。

这是我正在使用的示例电子表格:

Spreadsheet Example

下图可以看到上标文本复制到Word文档时已经转换为普通文本了:

Word Export

这是我的 VBA 宏:

Sub copyFromExcelToWord()

    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Dim myIndex As Integer
    Dim questionNumber As Integer
    Dim lastRow As Long

    lastRow = Cells(Rows.Count,1).End(xlUp).Row ' this figures out the last used row by counting backwards (up) from the bottom until it finds some data
    questionNumber = 1
   
     ' create a new word application and word document
    On Error Resume Next
    Set wrdApp = Getobject(,"Word.Application")
    On Error GoTo 0
    If wrdApp Is nothing Then
        Set wrdApp = CreateObject("Word.Application")
    End If
    wrdApp.Visible = True
    
    Set wrdDoc = wrdApp.Documents.Add ' create a new document
        
    ' insert the question and response data
    For myIndex = 2 To lastRow
        With wrdDoc.ActiveWindow.Selection
            .TypeText questionNumber & ". " & Range("A" & myIndex).Value    ' insert the question number and question text
            .TypeParagraph  ' insert a new paragraph ready for the responses
            
            .TypeText "a) " & Range("B" & myIndex).Value & Chr(11)  ' insert the first response data and goto a new line
            .TypeText "b) " & Range("C" & myIndex).Value & Chr(11)  ' insert the second response data and goto a new line
            .TypeText "c) " & Range("D" & myIndex).Value & Chr(11)  ' insert the third response data and goto a new line
            .TypeParagraph
            questionNumber = questionNumber + 1
        End With
    Next
    
    ' Save the word document into the WordExport Folder
    wrdDoc.SaveAs "c:\Data\testDocument.docx",FileFormat:=12 'wdFormatXMLDocument
    wrdDoc.Close ' close the document
    
    Set wrdDoc = nothing
    Set wrdApp = nothing
End Sub

有人可以提供一些提示,让我如何让这个宏正确显示上标和下标文本吗?

解决方法

不能在使用 .TypeText 时保留字符格式;您需要为此使用复制/粘贴。