繁体   English   中英

VBA:将特定单元格从 Excel 复制到 Word 上的表格中并格式化输出

[英]VBA: copying specific cells from Excel into a table on Word and formatting the output

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

我想从 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

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

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

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

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

暂无
暂无

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

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