我遇到错误问题:
Object'_Global'方法'范围'失败
...在第二次运行的代码段上。
整个程序是通过访问查询从SQL数据库导出信息并创建源表,然后导出到excel电子表格,源表包含来自14个不同位置的信息。因此,excel电子表格创建了14次(最终通过电子邮件发送给14个不同的人)
为了测试代码,我把它放在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
答案 0 :(得分:2)
当它坐下时,Range("G2")
可能会或可能不会引用 oSheet 工作表上的G2单元格。唯一可以肯定的是,它引用工作表上当前包含ActiveSheet property的G2单元格。
试一试,
.Cells.EntireRow.EntireColumn.Sort key1:=.Range("G2"), order1:=xlDescending, Header:=xlYes
注意.Range("G2")
而非Range("G2")
。这显式引用了使用With ... End With statement引用的工作表上的G2。