Word中使用VBA的不同excel实例之间的冲突

从一个MS Word文件,我有一个VBAmacros,必须打开一个不可见的模式,以从中获取数据的Excel。 问题是,当我启动macros时,它closures了其他正在运行的Excel实例,并显示一个'1004'运行时错误,指出<< _global对象的行方法失败>>。

Sub getDataFromExcel() Dim List Dim xlApp As Object Dim xlBook As Object Dim xlSheet As Object Dim xlSheetNum As Integer Dim iStarted As Boolean Dim lRow As Long Const strWorkBookName As String = "P:\Data_Source.xlsx" If Dir(strWorkBookName) = "" Then MsgBox "Cannot find the designated workbook: " & strWorkBookName, vbExclamation Exit Sub End If ' Test whether Excel is already running. On Error Resume Next iStarted = False ' Flag to record if we start Excel, so we can close it later. Set xlApp = GetObject(, "Excel.Application") 'Start Excel if it isn't running If xlApp Is Nothing Then Set xlApp = CreateObject("Excel.Application") If xlApp Is Nothing Then MsgBox "Can't start Excel.", vbExclamation Exit Sub End If ' Record that we've started Excel. iStarted = True End If On Error GoTo 0 Set xlBook = xlApp.Workbooks.Open(FileName:=strWorkBookName, ReadOnly:=True) xlApp.Visible = False 'Find the last non-blank cell in column A lRow = xlBook.Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row '<<< this line causes the error List = xlApp.Transpose(xlBook.Worksheets(1).Range("A2:A" & lRow).Value) ' Do something with List Set xlBook = Nothing xlApp.Quit Set xlApp = Nothing End Sub 

我怎样才能避免这种冲突?

限定您的Rows参考….

 lRow = xlBook.Worksheets(1).Cells(xlBook.Worksheets(1).Rows.Count, 1).End(xlUp).Row