我有一个会计系统,可以从SQL数据库创建报表,它将报表数据放在sheet1(报表)上,并在工作表2上报告参数。 当会计系统完成转储
时,我需要对数据进行排序并隐藏几列 在sheet1上的我输入以下代码
Private Sub Worksheet_Change(ByVal Target As Range)
Sort
HideExtraFields
End Sub
模块1中的
Sub Sort()
Selection.AutoFilter
ActiveWorkbook.Worksheets("Report").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Report").AutoFilter.Sort.SortFields.Add Key:=Range _
("E2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
ActiveWorkbook.Worksheets("Report").AutoFilter.Sort.SortFields.Add Key:=Range _
("D2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Report").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Selection.AutoFilter
End Sub
Sub HideExtraFields()
Columns("AA:AE").Select
Selection.EntireColumn.Hidden = True
End Sub
如果我将sheet1上的代码移动到ThisWorkbook,我会收到错误,因为它仍然在sheet2上倾倒参数
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Sort
HideExtraFields
End Sub
答案 0 :(得分:0)
您只是排序,排序不需要AutoFilter
;放弃它并放弃使用危险的Selection
东西。试试这种方式。
最好,我会将所有内容放在工作表Report
的代码模块中' Code Module of the worksheet Report
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
SortMe
HideExtraFields
End Sub
Sub SortMe()
With Me.Sort.SortFields
.Clear
.Add Key:=Me.Range("E2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
.Add Key:=Me.Range("D2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
End With
With Me.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.SetRange Me.UsedRange
.Apply
End With
End Sub
Sub HideExtraFields()
Me.Columns("AA:AE").Hidden = True
End Sub