VBA循环将数据从Excel提取到Word

时间:2017-09-28 20:57:09

标签: excel-vba ms-word vba excel

我已经花了太多时间寻找合适的答案,而我尝试的每一种方式都不会按照我想要的方式运作。

运行以下内容时,我收到引用Excel文件的“应用程序或对象定义错误”。它编译得很好,所以我不确定我哪里出错了。我需要它从Excel工作表上的两个不同位置提取数据,将它们放在Word文档中的特定定义标签中,使用自定义名称保存,并继续这样做直到Excel中列表的末尾。数据分别从A1和B1开始。

Dim oXL As Object
Dim oWB As Object
Dim exWb As String
Dim oSheet As Object
Dim bStartExcel As Boolean
Dim objDoc As Object
Dim fcount As Long
Dim iRow As Integer

exWb = "C:\Documents\Waivers_needed_0926_Take2.xlsx"

On Error Resume Next
'If Excel running use it
Set oXL = GetObject(, "Excel.application")

If Err.Number <> 0 Then 'If Excel isn't running then start it
bStartExcel = True
  Set oXL = CreateObject("Excel.Application")
End If

On Error GoTo Err_Handler
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=exWb)

'Process the worksheet
Set oSheet = oXL.ActiveWorkbook.Worksheets(4)
For iRow = 1 to 100

    With oSheet.Cells(iRow, 0)
        ActiveDocument.Amt_Paid.Caption = .Value
    End With

    With oSheet.Cells(iRow, 1)
        ActiveDocument.Payee.Caption = .Value
    End With

'Save Word Document with new name
fcount = fcount + 1
    With ActiveDocument
        .SaveAs FileName:="C:\Documents\Waivers\" & Split(ActiveDocument.Name, ".")(0) & "_" & Format(Now(), "YYYYMMDD") & "_" & fcount & ".doc"
    End With
Next iRow

Exit Sub

0 个答案:

没有答案