我一直在word文档中使用宏来将Excel工作簿中的数据输入到该MS Word文档中。
例程提示您查找存储数据的Excel工作簿,然后从工作簿中复制字段,在word文档文本中查找项目,然后将其替换为word文档文本。
以下代码正常运行,但偶尔会出现运行时错误。现在,每次执行都会出现以下错误。
运行时错误'1004'对象'_Global'的方法'工作表'失败
这条线触发:
.Replacement.Text =工作表(“1-组织服务区”)。范围(“B3”)。值'插入组织名称
代码要长得多,但这就是想法。在下面显示的第一个子上触发错误。
Sub InputContractData()
'
' You must pick Microsoft Excel Object Library from Tools>References
' in the Visual Basic editor to execute Excel commands.
' InputContractData Macro
'
'
'Define Excel and Workbook Information
Dim objExcelApp As Excel.Application
Dim objCDCDataWorkbook As Workbook
Dim CDCDataFile
Dim CDCDataFilePath
Dim CDCDataFileName
'Define Word and Document Information
Dim objWordApp As Word.Application
Dim objWordDoc As Word.Document
'Open Excel Program
Set objExcelApp = New Excel.Application
Set objWordApp = Word.Application
Set objWordDoc = objWordApp.ActiveDocument
objExcelApp.Visible = True
objWordApp.Visible = True
CDCDataFile = objExcelApp.GetOpenFilename("Excel Files (*.xlsx), *xlsx")
Set objCDCDataWorkbook = objExcelApp.Workbooks.Open(CDCDataFile)
CDCDataFilePath = Left(CDCDataFile, InStrRev(CDCDataFile, "\"))
CDCDataFileName = Dir(CDCDataFile)
Call Sheet001
'Save Document in same folder as CDC Workbook
objWordDoc.SaveAs CDCDataFilePath & "\DraftContract.docx"
' Close the new Word document.
objWordApp.ActiveDocument.Close
' Close the Word application.
objWordApp.Quit
End Sub
Sub Sheet001()
'Sheet 1- Organization Service Area -----------------------------
With Selection.Find
.ClearFormatting
.Text = "[[ORGANIZATION]]"
.Replacement.ClearFormatting
.Replacement.Text = Worksheets("1- Organization Service Area").Range("B3").Value 'Insert Organization Name
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
答案 0 :(得分:1)
行中的问题:
.Replacement.Text = Worksheets("1- Organization Service Area").Range("B3").Value 'Insert Organization Name
是MS Word不知道Worksheet
是什么,因为它不是Word对象模型中的本机对象。
如果您明确地将对象分配给它的正确父级,它将一直有效。由于Worksheet
是Excel中的对象,因此将其完全限定为Excel对象。我在下面显示了这一点,并选择将Excel工作簿传递给sub,因为您在InputContractData
过程中本地声明了变量。
Sub Sheet001(ws as Excel.Worksheet)
'Sheet 1- Organization Service Area -----------------------------
With Selection.Find
.ClearFormatting
.Text = "[[ORGANIZATION]]"
.Replacement.ClearFormatting
.Replacement.Text = ws.Range("B3").Value 'Insert Organization Name
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
然后这样打电话:
Sheet001 objExcelApp.Workbooks(CDCDataFileName).Worksheets("1- Organization Service Area")