Object'_Global'的方法'Range'第二次运行失败

我遇到了一个错误的问题:

Object'_Global'的方法'范围'失败

当它第二次运行时,在一段代码上。

整个程序是通过访问查询从SQL数据库导出信息,并创build源表然后导出到Excel电子表格,源表包含来自14个不同位置的信息。 Excel电子表格因此创build14次(最终通过电子邮件发送给14个不同的人)

为了testing代码的目的,我把它放在一个Do While循环来模拟代码不得不运行一次,我几十年来没有做任何编程,所以我非常生疏,代码段失败是:

.Cells.EntireRow.EntireColumn.Sort key1:=Range("G2"), order1:=xlDescending, Header:=xlYes 

完整代码:

 Private Function Open_Excel_Spreadsheet() Dim Cnt As Integer 'Counter Cnt = 1 Do While Cnt < 4 Dim oExcel As Excel.Application Dim oBook As Excel.Workbook Dim oSheet As Excel.Worksheet Dim LastRow As Long Dim FirstNewRow As Long Dim i As Integer 'Row counter in the range of 2 to FirstNewRow i = 2 Set oExcel = CreateObject("Excel.Application") Set oBook = oExcel.Workbooks.Open([MyDocsPath], , ReadOnly:=False) Set oSheet = oBook.Worksheets(1) oExcel.Visible = True 'Find the last used row in Column A and set LastRow and FirstNewRow variables With oSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With FirstNewRow = LastRow + 1 Debug.Print Cnt; FirstNewRow 'Format the Spreadsheet With oSheet .Sort.SortFields.Clear ' Next line generates "Method 'Range' of Object'_Global' Failed" the second time it runs .Cells.EntireRow.EntireColumn.Sort key1:=Range("G2"), order1:=xlDescending, Header:=xlYes .Cells(FirstNewRow, 5) = "=sum(E2:E" & [LastRow] & ")" .Cells(FirstNewRow, 6) = "=sum(F2:F" & [LastRow] & ")" For i = 2 To FirstNewRow .Cells(i, 7) = "=IF(+E" & [i] & "=0,0,Round(((+E" & [i] & "-F" & [i] & ")/E" & [i] & ")*100,2))" Next i .Range("E1:G1").EntireColumn.NumberFormat = "#,##0.00_);[Red]-#,##0.00" .Range("a1").EntireRow.EntireColumn.AutoFit End With 'Save Workbook and drop Excel oBook.Close True Cnt = Cnt + 1 Loop End Function 

当它坐下时, Range("G2")可能会或可能不会引用oSheet工作表上的G2单元格。 唯一可以确定的是,它指向当前拥有ActiveSheet属性的工作表上的G2单元格。

试试看,

 .Cells.EntireRow.EntireColumn.Sort key1:=.Range("G2"), order1:=xlDescending, Header:=xlYes 

注意。 .Range("G2")而不是Range("G2") 。 这明确引用了With With End With语句引用的工作表上的G2。