我從VB.NET創建一個Excel工作簿。兩個範圍的數據輸入到每張表中。範圍是三列寬由可變數量的行。數據輸入後,它被分類。排序工作在第一個範圍,但不是第二個 - 錯誤沒有了。從VB.NET中的Excel中排序兩個範圍不起作用
錯誤:COMException未處理。排序參考無效。確保它位於要排序的數據中,並且第一個「排序方式」框不相同或爲空。
我的代碼:
Dim xlApp As New Excel.Application
Dim xlWB As Excel.Workbook
Dim xlSht As Excel.Worksheet
Dim Rng As Excel.Range
Dim Rng2 As Excel.Range
'
Dim dic As Dictionary(Of UInteger, cVM)
Dim irow As UInteger
'
' create a new Excel Workbook instance
xlWB = xlApp.Workbooks.Add
'
' create a worksheet for each group
For Each key In dGroup.Keys
'
' create worksheet
xlSht = xlWB.Sheets.Add
xlSht.Name = key
'
'
' =======================================================
irow = 4
'
' output critical data, by Group
dic = New Dictionary(Of UInteger, cVM)
dic = dGroup(key).Dat
For Each lc In dic.Keys
xlSht.Cells(irow, 1) = lc
xlSht.Cells(irow, 2) = dic(lc).VM
xlSht.Cells(irow, 3) = dic(lc).EID
irow += 1
Next
'
' sort the output
Rng = xlSht.Range("A4", "C10000")
Rng.Select()
Rng.Sort(Key1:=Rng.Range("B4"), _
Order1:=Excel.XlSortOrder.xlDescending, _
Orientation:=XlSortOrientation.xlSortColumns) ' <== THIS WORKS !!!
'
'
'
' =======================================================
irow = 4
' output critical data, by Group
dic = New Dictionary(Of UInteger, cVM)
dic = dGroup2(key).Dat
For Each lc In dic.Keys
xlSht.Cells(irow, 5) = lc
xlSht.Cells(irow, 6) = dic(lc).VM
xlSht.Cells(irow, 7) = dic(lc).EID
irow += 1
Next
'
' sort the output
Rng2 = xlSht.Range("E4", "G10000")
Rng2.Select()
Rng2.Sort(Key1:=Rng2.Range("F4"), _
Order1:=Excel.XlSortOrder.xlDescending, _
Orientation:=XlSortOrientation.xlSortColumns) ' <== THIS IS WHERE IT ERRS OUT
'
Next key
第一個範圍爲A4:C10000。 第二個範圍是從E4:G10000。
排序第一範圍工作正常。排序第二個範圍不起作用。我不明白的是爲什麼?這是相同的代碼,除了我改變了範圍。我錯過了什麼?
好吧,這使得總感覺NOW。我沒有意識到這是一個相對的參考。關於「選擇」,從某個例子來說,我應該知道的更好。 – twegner