错误:"方法'行'对象' _Global'失败

时间:2017-08-02 04:08:32

标签: excel vba excel-vba word-vba

由于某种原因,即使我指的是oSheet变量,它也会返回错误,好像我指的是一个全局变量?

PS我试图用我创建的excel表中的承包商名称填充一个单词组合框。我在谷歌搜索过,不幸的是,没有一个解决方案对我有用。我认为错误在For Each声明中。

  Sub Macro3()

Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String

'specify the workbook to work on
WorkbookToWorkOn = "C:\Users\Nathan\Desktop\KTC\VBA Experiment\Excel Files\testExcel.xlsx"

'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")

If Err Then
   ExcelWasNotRunning = True
   Set oXL = New Excel.Application
End If

On Error GoTo Err_Handler

'If you want Excel to be visible, you could add the line: oXL.Visible = True here; but your code will run faster if you don't make it visible

'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)


'Process each of the spreadsheets in the workbook
For Each oSheet In oXL.ActiveWorkbook.Worksheets
   'put guts of your code here
   'get next sheet


 If oSheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
   lastRow = 2
   Else
   lastRow = oSheet.Cells(Rows.Count, 1).End(xlUp).Row
   End If

  ' For i = 2 To lastRow
  ' workZonerForm.contracterCMB.AddItem oSheet.Cells(i, 1)
  ' Next i


   MsgBox lastRow

Next oSheet

If ExcelWasNotRunning Then
  oXL.Quit
End If

'Make sure you release object references.
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing

'quit
Exit Sub

Err_Handler:
   MsgBox WorkbookToWorkOn & " caused a problem. " & Err.Description, vbCritical, _
           "Error: " & Err.Number
   If ExcelWasNotRunning Then
       oXL.Quit
   End If

End Sub

0 个答案:

没有答案