Home > Software engineering >  How to use VBA to excel data corresponding to fill in the word
How to use VBA to excel data corresponding to fill in the word

Time:09-27

As title, the corresponding data to fill in the word, and the content of the b column named word, a word to fill in multiple lines, if b column of figures change in another word tables, should how to write? Please answer thank orz on all points

CodePudding user response:

Start recording macros in Excel2003 and Word2003, manual, complete the required function end record macros, press Alt + F11 key, view the corresponding VBA macro code record just now,

CodePudding user response:

This is a VB program code, if you want to VBA in Excel/Word, oneself change, using the Excel. Application/Word. Application
 Option Explicit 

Sub Main ()
Dim xlApp As Excel. Application
Dim xlBook As Excel. The Workbook
Dim xlSheet As Excel. The Worksheet
Dim wdApp As Word. Application

The Set xlApp=New Excel. Application
The Set xlBook=xlApp. Workbooks. Open (App) Path & amp; "\ Book1. XLS")
The Set xlSheet=xlBook. Sheets (1)

The Set wdApp=New Word. Application

Export xlSheet, wdApp

WdApp. Quit
The Set wdApp=Nothing

The Set xlSheet=Nothing
XlBook. Close
The Set xlBook=Nothing
XlApp. Quit
The Set xlApp=Nothing
End Sub

Sub Export (ByVal xlSheet As Excel Worksheet, ByVal wdApp As Word. Application)
Dim xlTable As Excel. Range
Dim xlRowCount As Long
Dim xlColumnCount As Long
Dim wdDoc As Word. The Document
Dim wdTable As Word. Table
Dim wdRow As Long
Dim vLastGroup As the Variant
Dim As Long I
Dim j As Long

The Set xlTable=xlSheet. UsedRange
XlRowCount=xlTable. Rows. Count
XlColumnCount=xlTable. Columns. The Count

For I=1 To xlRowCount
If (wdTable Is Nothing) Or (xlTable Cells (I, 2). The Value & lt;> Then vLastGroup)
'save and close the old document'
If Not wdDoc Is Nothing Then
The Set wdTable=Nothing
WdDoc. SaveAs App. Path & amp; "" & amp; VLastGroup & amp; "Doc"
WdDoc. Close
The Set wdDoc=Nothing
End the If
'new document'
The Set wdDoc=wdApp. Documents. The Add ()
'add form'
WdApp. Selection. EndKey Unit:=wdStory
WdApp. Selection. TypeText Text:=xlTable Cells (I, 2)
WdApp. Selection. TypeParagraph

The Set wdTable=wdDoc. Tables. The Add (wdApp. The Selection Range, 1, xlColumnCount)
WdRow=1
VLastGroup=xlTable. Cells (I, 2). The Value
The Else
'add a line'
WdTable. Rows. The Add
WdRow=wdRow + 1
End the If

For j=1 To xlColumnCount
WdTable. Cell (wdRow, j) Range. The Text=xlTable. Cells (I, j). The Value
Next
Next

If Not wdDoc Is Nothing Then
The Set wdTable=Nothing
WdDoc. SaveAs App. Path & amp; "" & amp; VLastGroup & amp; "Doc"
WdDoc. Close
The Set wdDoc=Nothing
End the If
End Sub


Word screenshot (43 k) to life will not come up, you see the effect,
  •  Tags:  
  • VBA
  • Related