![](/img/trans.png)
[英]VBA to copy selected value of dropdown in Word Doc into specific Excel cell
[英]copy excel cell and paste it to specific word doc
我是VBA的新手,我需要将一个单元格(包含数据)从excel复制到特定的 (而不是从模板)word文档中。 特定文件的完整路径将位于目标单元格旁边的单元格中-offset(0,1)。 所有这些显然都处于循环中,因为我的清单很大,文件很多。
这是我的代码(该代码由我在搜索时捡到的某些部分组成)-但是我得到了
对象错误
Sub OpenWordFile()
Dim oWord As Object
Dim xRg As Object
Dim xCell As Range
Dim xVal As Range
Dim Workbook As Workbook
Dim FileName As Variant
'Word Object
Set oWord = CreateObject(Class:="Word.Application")
oWord.Visible = True
'Open Word Document (need to be multiple files in a loop)
'oWord.documents.Open FileName:="C:\Users\tamirre\Desktop\New folder\135-185844.doc" ' OPEN AN EXISTING FILE.
'Set oWord = Nothing
'Activating Excel to copy Cells
ThisWorkbook.Worksheets("Sheet1").Activate
Set xRg = Application.InputBox("Please select Cells to copy to word docs:", ActiveWindow.RangeSelection.Address, , , , , 8)
If xRg Is Nothing Then Exit Sub
For Each xCell In xRg
xVal = xCell.Value
Set FileName = xVal.Offset(0, 1) 'Cell Must Contain name and full path of the doc file
xVal.Copy
oWord.documents.Open FileName:="FileName"
Selection.EndKey Unit:=wdStory
Selection.TypeParagraph
Selection.PasteExcelTable True, False, False
Next
End Sub
InputBox
返回一个String
,而不是一个Object
。
将Dim
行更改为此:
Dim xRg As String
并将InputBox
行更改为此:
xRg = InputBox("Please select Cells to copy to word docs:", "Range Selection", ActiveWindow.RangeSelection.Address)
If xRg ="" Then Exit Sub
然后,如果要将其转换为Range
对象:
Dim xRange As Object
Set xRange = Range(xRg)
但是,我不建议您以此方式进行操作。 用户输入无效内容的机会太多,您会得到错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.