簡體   English   中英

VBA排序運行時錯誤438

[英]VBA sorting run time error 438

我在Access中使用VBA宏將數據放入Excel。 到目前為止,一切進展順利,但是現在我在Excel中有了數據,我想根據我創建的這個新列對數據進行排序。 我到處搜索了不同的排序語法示例,但是沒有任何效果。 最接近的是這給了我一個運行時錯誤438“對象不支持此屬性或方法”。 我要做的就是根據第一列的數據(僅數字)對整個工作表中的數據進行排序。

Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.Workbooks.Add
.Sheets("Sheet1").Select
End With

'More code is here in between that gets data into Excel file
'This code not shown works as expected 

With xlApp
.Range("A1").EntireColumn.Insert
.Cells(1, 1).Value = "DayOfWeek"
For i = 2 To 10000
    .Cells(i, 1).Value = Weekday(xlApp.Cells(i, 2).Value, vbMonday)
Next i
'Works as expected up to here, next line is problem
.Sort Key1:=.Range("A2"), Order1:=xlAscending
End With

編輯:在我初始化xlApp的部分中添加了代碼,並修復了Order1並將Value添加到Cells調用中,以使代碼更加清晰如所建議。 另外,應該注意的是,在調試中,我可以看到直到排序調用為止的所有內容都在Excel工作簿中給出了正確的輸出。

    With xlApp
        .Range("A1").EntireColumn.Insert
        .Cells(1, 1).Value = "DayOfWeek"
        For i = 2 To 10000
            .Cells(i, 1) = Weekday(.Cells(i, 2), vbMonday)
        Next i
        'Works as expected up to here, next line is problem
        .Cells.Sort Header:=xlYes, Key1:=.Range("A2"), Order1:=xlAscending
    End With

我認為這里有很多問題:

  1. 我懷疑xlApp是Application對象,您試圖在其中對Worksheet對象運行操作。 用已聲明並分配給Worksheet另一個變量替換xlApp ,或僅使用Activesheet

  2. 優良作法是,應始終引用Cell對象的.Value屬性,而不要依賴默認屬性。 這使閱讀和維護更加容易。

  3. Sort方法不適用於Worksheet級別,但不能作用於Range對象。

  4. 參數Order不存在。 Order1 ,它是Key1補充。

  5. 據我所知,第1行有標題。您需要修改Sort語句以跳過對標題的排序。

這是最后的代碼塊:

With xlApp.ActiveSheet
  .Range("A1").EntireColumn.Insert
  .Cells(1, 1).Value = "DayOfWeek"
  For i = 2 To 10000
    .Cells(i, 1).Value = Weekday(.Cells(i, 2).Value, vbMonday)
  Next i
  'Works as expected up to here, next line is problem
  .Range("A1").Sort Key1:=.Range("A1"), Order1:=xlAscending, Header:=xlYes
End With

在對范圍進行排序之前,必須先選擇范圍:

Dim RngRange As Range
Set RngRange = Sheet.Range("A1:A999")
RngRange.Select
RngRange.Sort Key1:=RngRange, Order1:=xlAscending

如果要排序一列並在結果中包括另一列,則RngRange是要排序的所有列,關鍵是要排序的列

在線上的大多數示例實際上都是錯誤的,令我發瘋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM