【问题标题】:Copying text from Word to Excel while keeping the formatting (using .typetext)在保留格式的同时将文本从 Word 复制到 Excel(使用 .typetext)
【发布时间】:2021-06-10 03:06:55
【问题描述】:

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

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

您可以在下面看到上标文本在复制到Word文档时已转换为普通文本:

这是我的 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

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

【问题讨论】:

    标签: excel vba ms-word


    【解决方案1】:

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

    【讨论】:

    • 谢谢@macropod。我刚才一直在尝试复制和粘贴信息,如下所示:'.TypeText questionNumber & "." Range("A" & myIndex).Copy .Paste' 但是它运行了一段时间然后给了我这个错误: 运行时错误“4605”此方法或属性不可用,因为剪贴板为空或无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    相关资源
    最近更新 更多