2017-06-01 56 views
0

我是VBA腳本編程的新手,並且想要編寫一個VBA腳本來按多列對Excel表進行排序。列的數量可以在工作表中有所不同,但我需要考慮兩個用於排序的列,即第一個&最後一列。例如。這裏有兩個不同的Excel表格,我需要根據第一個&最後一列排序,即ID & RANK。通過動態確定鍵列來排序Excel工作表

enter image description here

enter image description here

sheet1 sheet2

我試着用下面動態發現最後一欄

LastColumn = Split(sht.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$") 
(0) 

但我不能夠使用上述在Range方法中用於選擇鍵的變量。

它引發運行時錯誤。

是否有任何方式使用變量來選擇範圍或任何其他方式來實現這種排序。

在此先感謝。

+2

你怎麼申報'LastColumn()'?一般來說,我做'Dim lastColumn as Long'然後'LastColumn = sht.cells(1,sht.columns.count).End(XlToLeft).Column',並返回列號... – BruceWayne

+0

我剛纔宣佈LastColumn爲字符串,並返回最後一列字母而不是列號。 –

+1

使用像@BruceWayne所述的列號,並使用'Range()'中的'Cells(RowNumber,ColumnNumber)' –

回答

0

如果我正確地讀出你的評論,你當前的代碼(添加幾個換行符)是

Set sht = Workbooks("test_vba.xlsx").Worksheets("Sheet1") 
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 
LastColumn = sht.cells(1,sht.columns.count).End(XlToLeft).Column 
sht.Range(Cells(1, 1), _ 
      Cells(1,LastColumn) & Sheets("sheet1").Range("A1").End(xlDown).Row).Sort _ 
      Key1:=sht.Range("A:A"), _ 
        Order1:=xlAscending, _ 
      Key2:=sht.Range(Cells(1,LastColumn), Cells(LastRow,LastColumn)), _ 
        Order2:=xlDescending, _ 
      Header:=xlYes 

,因爲你是從最後一列上取本節說Cells(1,LastColumn) & Sheets("sheet1").Range("A1").End(xlDown).Row有問題第1行並將列A中最後一行的行號添加到該行中 - 這不會給你一個Range

我相信你正在尋找的東西,如:

Dim LastRow As Long 
Dim LastColumn As Long 
Dim sht As Worksheet 

Set sht = Workbooks("test_vba.xlsx").Worksheets("Sheet1") 
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 
LastColumn = sht.Cells(1, sht.Columns.Count).End(xlToLeft).Column 

sht.Range(sht.Cells(1, "A"), sht.Cells(LastRow, LastColumn)).Sort _ 
      Key1:=sht.Columns(1), Order1:=xlAscending, _ 
      Key2:=sht.Columns(LastColumn), Order2:=xlDescending, _ 
      Header:=xlYes 
+0

謝謝@YowE3K,它的工作。 –