运行-时间错误“1004”:在 sheetchange 中排序

Run-time error '1004': Sorting in sheetchange

我在使用排序宏时遇到了简单的问题。当我从我的其他工作簿导入数据时,工作簿 运行 SheetChange 下面的宏并收到 运行-time 错误。 但是,如果我在工作簿打开时只 运行 宏,它就完全可以正常工作。

我不知道我是否必须用 ActiveWorkbook 或其他东西替换 Range,但我想我已经尝试了很多不同的东西,但仍然没有运气:(

我希望它从 B 列开始排序,从第 13 行开始,直到最后 row/column。它是动态的,所以每次我导入东西时它都会改变。

Sub TESTSORT()
Dim startCol, myCol As String
Dim startRow, lastRow, lastCol As Long
Dim ws As Worksheet
Dim Rng, cell As Range

Application.ScreenUpdating = False
Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
startCol = "A"
startRow = 13
lastRow = ws.Range(startCol & ws.Rows.Count).End(xlUp).Row
'lastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
lastCol = ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count).Column

myCol = GetColumnLetter(lastCol)

Set Rng = ws.Range(startCol & startRow & ":" & myCol & lastRow)

' I GET THE ERROR HERE
Range(.Cells(13, 1), .Cells(lastRow, lastCol)).Sort key1:=Range("B13:B" & lastRow),
order1:=xlAscending, Header:=xlNo

End With
Application.ScreenUpdating = True
End Sub

Function GetColumnLetter(colNum As Long) As String
Dim vArr
vArr = Split(Cells(1, colNum).Address(True, False), "$")
GetColumnLetter = vArr(0)
End Function

您的 With 语句中似乎有一些问题...在多个地方使用 Range 而不是 .Range。我试着在下面稍微清理一下...

Sub TESTSORT()
Dim startCol, myCol As String
Dim startRow, lastRow, lastCol As Long
Dim ws, ws2 As Worksheet
Dim Rng, cell As Range

Set ws2 = ActiveSheet 'Preserves a reference to the active sheet as ws2
ThisWorkbook.Activate 'Makes this workbook the one that is displayed

Application.ScreenUpdating = False
Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    startCol = "A"
    startRow = 13
    lastRow = .Range(startCol & .Rows.Count).End(xlUp).Row
    'lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
    lastCol = ws2.UsedRange.Columns(ws2.UsedRange.Columns.Count).Column

    myCol = GetColumnLetter(lastCol)

    Set Rng = .Range(startCol & startRow & ":" & myCol & lastRow)

    ' I GET THE ERROR HERE
    .Range(.Cells(13, 1), .Cells(lastRow, lastCol)).Sort key1:=.Range("B13:B" & lastRow),
    order1:=xlAscending, Header:=xlNo

    End With
Application.ScreenUpdating = True
End Sub

Function GetColumnLetter(colNum As Long) As String
Dim vArr
vArr = Split(Cells(1, colNum).Address(True, False), "$")
GetColumnLetter = vArr(0)
End Function