我的宏有问题,我想知道是否有人可以帮助我。 我在一个文件中做一个宏,该宏将访问其他文件并对那里存在的信息进行排序。到目前为止,我有以下代码:
Sub Macro()
Dim xl As New Application
Dim xlw As Workbook
Dim xls As Worksheet
a = ThisWorkbook.Path & "\A.csv"
On Error GoTo bm:
Set xlw = xl.Workbooks.Open(a)
Set xls = xlw.Sheets(1)
' Windows(a).Activate
a = xls.Name
Columns("C:C").Select
xlw.Worksheets(a).Sort.SortFields.Clear
xlw.Worksheets(a).Sort.SortFields.Add Key:=Range("C2"), SortOn _
:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With xlw.Worksheets(a).Sort
.SetRange Range("A2:K297594")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
bm:
xlw.Saved = True
xlw.Close True
xl.Quit
Set xls = Nothing
Set xlw = Nothing
Set xl = Nothing
End Sub
当它运行时,当它到达指令“.SetRange Range(”A2:K297594“)时”它给出“运行时错误5”,我不明白为什么。所以任何人都可以解释我如何解决这个或为什么给出这个错误?
谢谢:)
答案 0 :(得分:1)
您的范围未被引用,Excel不知道您正在谈论的是哪个工作表,它应该是.SetRange xlw.Worksheets(a).Range("A2:K297594")
:
Sub Macro()
Dim xl As New Application
Dim xlw As Workbook
Dim xls As Worksheet
a = ThisWorkbook.Path & "\A.csv"
On Error GoTo bm:
Set xlw = xl.Workbooks.Open(a, Local:=True)
Set xls = xlw.Sheets(1)
' Windows(a).Activate
a = xls.Name
Columns("C:C").Select
xlw.Worksheets(a).Sort.SortFields.Clear
xlw.Worksheets(a).Sort.SortFields.Add Key:=xlw.Worksheets(a).Range("C2"), SortOn _
:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With xlw.Worksheets(a).Sort
.SetRange xlw.Worksheets(a).Range("A2:K297594")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
bm:
xlw.Save
xlw.Close True
xl.Quit
Set xls = Nothing
Set xlw = Nothing
Set xl = Nothing
End Sub
答案 1 :(得分:1)
您需要限定所有工作簿,工作表和范围引用,特别是因为您正在针对宏运行的其他工作簿运行宏。
你真的差不多(99%)。这将为您清理它:
{{1}}