将信息sorting在不同的文件excel中

我的macros有一个问题,我想知道是否有人可以帮助我。 我在一个文件中做一个macros,这个macros将访问其他文件并对存在的信息进行sorting。 到现在为止,我有以下代码:

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 

当它运行,当它到达指令“.Range Range(”A2:K297594“)”它给“运行时错误5”,我不明白为什么。 那么任何人都可以解释我是如何解决这个问题,或者为什么会出现这个错

谢谢 :)

您的范围没有被引用,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 

您需要限定所有工作簿,工作表和范围引用,特别是因为您正在运行一个macros来运行macros从其中运行的另一个工作簿。

你几乎在那里(99%)。 这将为你清理它:

  Dim wName as String 'since you already use a to get the file name wName = xls.Name With xlw.Worksheets(wName).Sort With .SortFields .Clear 'note . (period) in front of range and I am pretty sure you need to set the 'whole range reference ... hence the C297597 ... but maybe just C2 is enough .Add Key:=.Range("C2:C297594"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal End With 'note . (period) in front of range .SetRange .Range("A2:K297594") .Header = xlNo .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With