【问题标题】:VBA: copying specific cells from Excel into a table on Word and formatting the outputVBA:将特定单元格从 Excel 复制到 Word 上的表格中并格式化输出
【发布时间】:2020-12-12 17:04:34
【问题描述】:

我不是一个编码员,但我在网上找到了一个源代码外壳并一直在对其进行调整,尽管没有完全理解它在做什么,现在我终于遇到了一个问题。我不知道如何格式化复制的值。我确信总有一种更简洁的方法可以做到这一点,如果我可以复制它以获得我想要的东西,我会全力以赴!

我想从 Excel 电子表格中提取某些单元格并将它们放入一个特定样式和格式的表格中。

Option Explicit
Const FilePath As String = "C:\Users\nicho\Final2\"
Dim wd As New Word.Application

Sub ExportButton()

Dim doc As Word.Document
wd.Visible = True

Dim J As String
Dim C As String
Dim F As String
Dim G As String
Dim E As String
Dim D As String

J = ThisWorkbook.Sheets(1).Range("J2").Value   'value from sheet1
C = ThisWorkbook.Sheets(1).Range("C2").Value
F = ThisWorkbook.Sheets(1).Range("F2").Value
G = ThisWorkbook.Sheets(1).Range("G2").Value
E = ThisWorkbook.Sheets(1).Range("E2").Value
D = ThisWorkbook.Sheets(1).Range("D2").Value

Set doc = wd.Documents.Open(FilePath & "output.docx")
Copy2word "JField", J
Copy2word "CField", C
Copy2word "FField", F
Copy2word "GField", G
Copy2word "EField", E
Copy2word "DField", D

doc.Close

wd.Quit
'MsgBox "Created files in " & FilePath & "!"

End Sub
Sub Copy2word(BookMarkName As String, Text2Type As String)
'copy each cell to relevant Word bookmark
wd.Selection.GoTo What:=wdGoToBookmark, Name:=BookMarkName
wd.Selection.TypeText Text2Type
End Sub

对不起,如果这是一个愚蠢的问题,我已经搜索并没有设法找到我正在使用的代码的解决方案。

【问题讨论】:

  • 那么您的问题是找不到将要复制到 Word 文档的文本格式化的方法吗?

标签: excel vba ms-word formatting


【解决方案1】:

在 Excel 或 Word 中使用 VBA 时,始终建议避免使用 Selection 对象。因此,您的 Copy2Word 例程可以重写如下。这将允许您添加所需的任何格式。您可以通过在 Word 中录制宏来获取该格式的基本代码。尽管宏记录器将使用Selection 对象,但您会发现Range 可以使用相同的对象。您还可以使用对象浏览器和 Intellisense 来检查您的代码是否有效。

当然,如果书签位置已使用样式正确格式化,则无需应用任何格式。

Sub Copy2word(targetDoc As Word.Document, BookMarkName As String, Text2Type As String)
  If targetDoc.Bookmarks.Exists(BookMarkName) Then
    With targetDoc.Bookmarks(BookMarkName).Range
      .text = Text2Type
      'add formatting code here
    End With
  End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多