[英]Pull particular Excel cell value into Word document using Word VBA
I am new to VBA and macros.我是 VBA 和宏的新手。
I got the repeated task of copy data from Excel and paste it in a particular location in the word document.我得到了从 Excel 复制数据并将其粘贴到 word 文档中的特定位置的重复任务。
For example, my excel sheet has the data like this:例如,我的 excel 表有这样的数据:
Col1 ![]() |
Col2 ![]() |
---|---|
ID_1 ![]() |
I'm_One![]() |
ID_2 ![]() |
I'm_Two![]() |
ID_3 ![]() |
I'm_Three![]() |
Now i'm looking for a Word macro现在我正在寻找一个 Word 宏
[Update] I have tried with multiple code snippets by google search but unable to construct the working macro. [更新] 我通过谷歌搜索尝试了多个代码片段,但无法构建工作宏。
Sub pull_from_Excel2()
'ref: https://www.macworld.com/article/211753/excelwordvisualbasic.html
Dim Month As String
ID_Range = "A2:A6" 'Select this as range like "A2:A16"
Offset_to_fetch = 1 'Select this to fetch comments etc. value starts with
Set xlSheet = GetObject("D:\Excel.xlsx")
'Snippets:
'Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range("A3:A5").Value)
'8204
Dim Cell As Range, rng As Range
Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range(ID_Range).Value2)
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
For Each Cell In rng
Debug.Print Cell.Text
Next Cell
End Sub
I used this url to construct my skeleton code: https://www.macworld.com/article/211753/excelwordvisualbasic.html我用这个 url 来构建我的骨架代码: https://www.macworld.com/article/211753/excelwordvisualbasic.ZFC35FDC70D5FC69D269883A822C7A5E3
When i try to get the values from the range of cells in excel, i got the following error for the code.当我尝试从 excel 中的单元格范围获取值时,我收到以下代码错误。
Set rng = xlSheet.Worksheets(1).Range(ID_Range).Value2
The above line gives "Object required" error when running.上面的行在运行时给出“需要对象”错误。
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
The above line gives "Type Mismatch" error when running.上面的行在运行时给出“类型不匹配”错误。 Notes: For this error, I tried to use for each loop as this is array but the error is showing before executing the for loop.
注意:对于这个错误,我尝试使用 for 每个循环,因为这是数组,但在执行 for 循环之前显示错误。
Kindly assist.请协助。
I recommend to use Option Explicit
and declare all your varibales properly.我建议使用
Option Explicit
并正确声明所有变量。 This way it is less likely that you end up with unseen errors.这样,您就不太可能出现看不见的错误。
To activate it for all new codes that you add in the future, you can activate it directly in Excel and Word.
要为您将来添加的所有新代码激活它,您可以直接在 Excel 和 Word 中激活它。 This is a good practice and will protect you from doing it wrong by notifying you of not declared variables:
这是一个很好的做法,可以通过通知您未声明的变量来防止您做错:
In the VBA editor go to Tools › Options › Require Variable Declaration .
在 VBA 编辑器 go 到Tools › Options › Require Variable Declaration 。
This will add
Option Explicit
to new modules only.这只会将
Option Explicit
添加到新模块。 In existing modulesOption Explicit
needs to be added manually as first line.在现有模块中
Option Explicit
需要手动添加为第一行。
Further I highly recommend to name your variables according what they contain because otherwise it gets very confusing.此外,我强烈建议根据变量包含的内容命名变量,否则会变得非常混乱。 You named your variable
xlSheet
but you load a workbook into it and not a worksheet.您将变量命名为
xlSheet
,但您将工作簿而不是工作表加载到其中。
The next issue is that your code is in Word and if you declare rng As Range
then this is of type Word.Range
and not Excel.Range
and those are diffetent types so that is why you get a "Type Mismatch" error.下一个问题是您的代码在 Word 中,如果您将
rng As Range
,那么这是Word.Range
类型而不是Excel.Range
类型,它们是不同的类型,因此您会收到“类型不匹配”错误。 To solve this you either go in Word VBA to Extras › Refereces … and set a reference to the Excel library so you can declare your variable Dim xlRng As Excel.Range
or if you don't set a reference you declare it as Object
or Variant
like in below example: To solve this you either go in Word VBA to Extras › Refereces … and set a reference to the Excel library so you can declare your variable
Dim xlRng As Excel.Range
or if you don't set a reference you declare it as Object
or Variant
如下例所示:
' This code is in Word!
Option Explicit
Public Sub pull_from_Excel2()
'declare constants
Const ID_Range As Sting = "A2:A6" 'Select this as range like "A2:A16"
Const Offset_to_fetch As Long = 1 'Select this to fetch comments etc. value starts with
Dim xlWorkbook As Object
Set xlWorkbook = GetObject("D:\Excel.xlsx") 'This expects the Excel to be already open! If not open you need to use CreateObject("Excel.Application")
Dim xlRng As Object
Set xlRng = xlWorkbook.Worksheets(1).Range(ID_Range)
Dim xlCell As Object
For Each xlCell In xlRng
Debug.Print xlCell.Text
Next xlCell
End Sub
Note if your workbook Set xlWorkbook = GetObject("D:\Excel.xlsx")
is not open in Excel you need to use CreateObject("Excel.Application")
and open it.请注意,如果您的工作簿
Set xlWorkbook = GetObject("D:\Excel.xlsx")
未在 Excel 中打开,则需要使用CreateObject("Excel.Application")
并打开它。
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Dim xlWorkbook As Object
Set xlWorkbook = xlApp.Workbooks.Open(FileName:="D:\Excel.xlsx") 'will open the workbook
xlApp.Visible = True 'make it false to open Excel invisible in the background
'your code here …
'in the end close workbook and Excel (espaciall if you had it invisible!)
xlWorkbook.Close SaveChanges:=False
xlApp.Quit 'close Excel
Option Explicit
Sub UpdateTables()
Const XLSX = "D:\Excel.xlsx"
Dim xlApp, wb, ws
Dim rngSearch, rngFound
Dim iLastRow As Long, n As Integer
' open spreadsheet
'Set xlApp = New Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(XLSX, 1, 1)
Set ws = wb.Sheets(1)
iLastRow = ws.Cells(ws.Rows.Count, "A").End(-4162).Row 'xlUp
Set rngSearch = ws.Range("A2:A" & iLastRow)
' update tables
Dim doc As Document, tbl As Table, s As String
Set doc = ThisDocument
For Each tbl In doc.Tables
s = tbl.Cell(1, 1).Range.Text
s = Left(s, Len(s) - 2)
Set rngFound = rngSearch.Find(s, LookIn:=-4163, LookAt:=1) ' xlValues, xlWhole
If rngFound Is Nothing Then
MsgBox "'" & s & "' not found in table " & tbl.Title, vbExclamation
Else
tbl.Range.Cells(3).Range.Text = rngFound.Offset(0, 1)
n = n + 1
End If
Next
wb.Close False
xlApp.Quit
MsgBox n & " tables updated", vbInformation
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.