我正在从Excel文件运行VBA脚本,该文件打开另一个文件,操纵数据和一些图表,然后保存它。除非我尝试对数据进行排序,否则一切都很完美。当我到达.SortFields.Add Key:=Range("J3:J11")...
行时出现错误
Run-time error '-2147417851 (80010105)':
Automation error
The server threw an exception
我确定它与我引用Excel对象的方式有关,但我已经尝试了一切,似乎无法找到解决方案。分类代码是从宏录制器中借来的并进行了修改。
Private Sub button1_Click()
Dim path As String
Dim exl As Excel.Application
path = ActiveWorkbook.path & "\"
Set exl = CreateObject("Excel.Application")
With exl
.Workbooks.Open path & "bin\Integrated UPSIDE with Summary.xlsm"
<...other code...>
With .Worksheets("Summary").Sort
.SortFields.Clear
.SortFields.Add Key:=Range("J3:J11") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange Range("C2:P11")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
<...other code...>
.Workbooks.Close
End With
exl.QUIT
End Sub
非常感谢任何建议!感谢
答案 0 :(得分:0)
问题是您没有正确引用您的范围。您正在使用的排序代码是为当前Excel实例中的活动工作表上的排序范围编写的。
解决此问题的最简单方法是将范围引用为另一个Excel实例。
.SortFields.Add Key:=exl.Worksheets("Summary").Range("J3:J11") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange exl.Worksheets("Summary").Range("C2:P11")
但是,我的建议是使用Workbook和Worksheet对象。
Private Sub button1_Click()
Dim path As String
Dim exl As Excel.Application
Dim wbk As Workbook, sht As Worksheet
path = ActiveWorkbook.path & "\"
Set exl = CreateObject("Excel.Application")
With exl
Set wbk = .Workbooks.Open(path & "bin\Integrated UPSIDE with Summary.xlsm")
'<...other code...>
Set sht = wbk.Worksheets("Summary")
With sht.Sort
.SortFields.Clear
.SortFields.Add Key:=sht.Range("J3:J11") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange sht.Range("C2:P11")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'<...other code...>
wbk.Close
Set sht = Nothing
Set wbk = Nothing
End With
exl.Quit
End Sub