简体   繁体   中英

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

I'm not much of a coder, but I found a shell of source code online and have been tweaking it, despite no fully understanding what it's doing and now I've finally run into a problem. I don't have the slightest clue how to format the copied values. I'm sure there's a cleaner way of doing this in all and if it's possible for me to replicate it to get what I want, I'm all ears!

I want to take certain cells from an excel spread sheet and place them into a specifically styled and formatted table.

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

Sorry if this is a stupid question, I've searched and haven't managed to find a solution with the code that I'm using.

When working in VBA, either in Excel or Word, it always advisable to avoid using the Selection object. Your Copy2Word routine can therefore be rewritten as below. This will allow you to add whatever formatting you need. You can get the essential code for that formatting by recording a macro in Word. Although the macro recorder will use the Selection object you will find that the same objects are available to the Range . You can also use the Object Browser and Intellisense to check that your code is valid.

Of course if the bookmarked locations are already properly formatted using styles you won't need to apply any formatting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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