【发布时间】:2017-11-03 02:51:27
【问题描述】:
我是 VBA 脚本的新手,想编写一个 VBA 脚本来按多列对 Excel 工作表进行排序。工作表中的列数可能会有所不同,但我需要考虑两列进行排序,即第一列和最后一列。例如。这是两个不同的 Excel 表,我需要根据第一列和最后一列(即 ID 和 RANK)对其进行排序。
我尝试使用以下方法动态查找最后一列:
LastColumn = Split(sht.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")
(0)
但是我无法在 Range 方法中使用上述变量来选择键。
它抛出运行时错误。
有没有什么方法可以使用变量来选择Range或者任何其他的方式来实现这种排序。
提前致谢。
【问题讨论】:
-
你是如何声明
LastColumn()的?一般来说,我先做Dim lastColumn as Long然后LastColumn = sht.cells(1,sht.columns.count).End(XlToLeft).Column,然后返回列号... -
我刚刚将 LastColumn 声明为 String,它返回最后一列字母而不是列号。
-
使用@BruceWayne 所述的列号并使用
Cells(),它采用列号Cells(RowNumber,ColumnNumber) -
我在
Range()中使用了Cells(RowNumber,ColumnNumber),但它再次给出了运行时错误。下面是我的代码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