vba 位 前 相似 筛选,VBA中的自动筛选排序

I'm making a VBA macro. At one point, the macro tells excel to change the current autofilter to have the autofilter's sort be on the column in Column A, and it should be ascending.

But, the VBA code that I have now states that the RANGE is hard-coded which is Range(A1:A655),that's because the code was written in a recorded Macro. Below is my VBA code. Can you tell me how to change the A1:A655 not in a hard-coded way, instead make it just generically mean "make the range be ALL of the rows in that column, however much there is?

ActiveWorkbook.Worksheets("A1").AutoFilter.Sort.SortFields.Add Key:=Range(

"A1:A655"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=

xlSortTextAsNumbers

解决方案

Try to avoid relying on the ActiveSheet property. You should know what worksheet you are on and explicitly reference it by the Worksheet .CodeName or

Worksheet .Name property.

I believe you've mixed up a Worksheet Object with a Range object. That is, unless you actually have a worksheet named A1 which does not seem likely.

The Range.CurrentRegion property is an excellent method of referencing the uninterrupted block of cells radiating out from A1. It continues down and right until it meets a fully blank row and fully blank column. Single or small groups of intermediate blank cells do not interrupt its reference to the block of cells.

With ActiveWorkbook

With .Worksheets("Sheet1")

If .AutoFilterMode Then .AutoFilterMode = False

With .Cells(1, 1).CurrentRegion

.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _

Orientation:=xlTopToBottom, Header:=xlYes

With .Resize(.Rows.Count, 141) '

.AutoFilter Field:=36, Criteria1:=1

'the CurrentRegion is sorted on column A and filtered

'on column AJ

End With

End With

End With

End With

The nested With ... End With statements progessively defines the block of cells you wish to reference.

I believe you are better off with a conventional Range.Sort method. It is more straightforward than a .AutoFilter.Sort. A subsequent AutoFilter method finishes off the operation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值