简体   繁体   中英

Excel VBA Sorting sheet when workbook is hidden

Hi guys I'm using a sorting code it was working fine until it didn't after a while of reading though the code and testing I found that the reason for the error was because of the select which as far as I know only work when you can select the sheet first with a visible worksheet and here comes my problem I need the code to work with a hidden workbook anybody that can help with getting the code to work with hidden workbook because I only know this code. Thanks!

what the code here does is sorting after B column but it have the row 1 as header

Set tsheet = ThisWorkbook.Sheets("Courses_tee")

    ThisWorkbook.Sheets("Courses_tee").Range("B2").CurrentRegion.Select
    Selection.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal

Change this:

ThisWorkbook.Sheets("Courses_tee").Range("B2").CurrentRegion.Select
Selection.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal

To this:

Set tsheet = ThisWorkbook.Sheets("Courses_tee")
tSheet.Range("B2").CurrentRegion.Sort Key1:=Range("B2"), _
    Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal

You don't need to, and you shouldn't Select or Activate things when you can operate directly on the objects instead. Select and Activate essentially mimic keystrokes/mouse-clicks/user actions -- you don't need to Select a range in your code if you know what that range is , ie:

Range("A1:A100").Select
Selection.Copy Destination:=Range("B1")

Can become simply:

Range("A1:A100").Copy Destination:=Range("B1")

Etc.

More info:

How to avoid using Select in Excel VBA

You don't need to select

tSheet.Range("B2").CurrentRegion.Select
Selection.Sort Key1:=tSheet.Range("B2"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM