我经常使用工资核算数据格式化工作表。它每次都有相同的布局,但长度不同,取决于当周工作的员工数量。我在创建一个适用于不同行数的宏时遇到了麻烦。错误是“运行时错误'9':下标超出范围”,发生在第22行。我的猜测是,这是因为它指的是特定的工作表,而不仅仅是打开的。非常感谢任何帮助!
https://pastebin.com/embed_js/VV6d6De8“>
' WLM_2 Macro
'
'
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Columns("A:C").Select
Selection.Columns.AutoFit
Columns("B:B").Select
ActiveWorkbook.Worksheets("WeeklyLaborHours (5)").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("WeeklyLaborHours (5)").Sort.SortFields.Add Key:= _
Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("WeeklyLaborHours (5)").Sort
.SetRange Range("A2:V371")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
答案 0 :(得分:0)
我相信你的怀疑是对的。如果在运行宏时选择了WeeklyLaborHours (5)
以外的工作表,则会失败。如果在调用范围时未指定工作表,则默认为选定的工作表。下面的代码应该更正错误,但它假定您要在活动工作表上的排序字段命令之前执行所有操作,而不是专门在WeeklyLaborHours (5)
上执行。
Public Sub WLM_2()
'WLM_2 Macro
'
Dim wsWLH5 As Worksheet
Set wsWLH5 = ActiveWorkbook.Worksheets("WeeklyLaborHours (5)")
'
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Columns("A:C").Select
Selection.Columns.AutoFit
Columns("B:B").Select
With wsWLH5.Sort
.SortFields.Clear
.SortFields.Add Key:=wsWLH5.Range("B1"), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.SetRange wsWLH5.Range("A2:V371")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
答案 1 :(得分:0)
我已删除了您的Select和硬编码工作表参考,并将代码集中在ActiveWindow和ActiveSheet上。
Sub WLM_2()
' WLM_2 Macro
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
With ActiveSheet
.Columns("A:A").Delete Shift:=xlToLeft
.Columns("C:F").Delete Shift:=xlToLeft
.Columns("A:C").AutoFit
With .Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp).Offset(0, 21))
.Sort Key1:=.Columns(2), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlNo
End With
.Columns("B:B").Select
End With
End Sub
我还将四个连续的列删除命令聚合到一个删除中,并将.Sort命令缩减为您实际需要的内容。