Sort not executing properly in macro unless run by itself

SDPanda

New Member
Joined
Jan 29, 2023
Messages
7
Office Version
  1. 365
Platform
  1. Windows
Hello everybody,
New to VBA coding. I have a dynamic table that is created from a macro based on another worksheet, a query, and equations. I then have a different module with the following:

VBA Code:
Sub SortTable(ws As Worksheet, tableName As String)
 
    Dim tbl As ListObject
    Set tbl = ws.ListObjects(1)

    tbl.Sort.SortFields.Clear

    tbl.Sort.SortFields.Add2 Key:=tbl.ListColumns("Requested Lot").DataBodyRange, _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

    tbl.Sort.SortFields.Add2 Key:=tbl.ListColumns("Standardized Conc (uM)").DataBodyRange, _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    
    With tbl.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .Apply
    End With

End Sub


When I call this subroutine directly from the one creating the table, the sort is not executed properly. However, if I execute the macro manually, the rows are sorted correctly. I suspect the calculations are not fully complete by the time its executing, or that the screen needs time to update. Any suggestions would be great. Thank you
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
The macro that precedes the sort function:

VBA Code:
Sub PerformDiluentCalcs_()
    
    ' Turn off screen updating
    Application.ScreenUpdating = False
    
    ' Define the worksheet, table, and formula ranges
    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim sheettbl As ListObject
    Dim formulaColumn As Range
    
    ' Prevent macro from running unless an option is selected
    Dim optPlate As Object
    Dim optCell As Object
    
    Set optPlate = ws.OLEObjects("optPlate").Object
    Set optCell = ws.OLEObjects("optCell").Object
    
    ' Check which option button is selected
    If optPlate.value = True Then
        ' Do something when "Plate" is selected
    ElseIf optCell.value = True Then
        ' Do something when "Cell" is selected
    Else
        MsgBox "Please select an UV Analysis Method before proceeding."
        Exit Sub
    End If
    
    ' Check if any of the option buttons are selected
    If Not optPlate.value And Not optCell.value Then
        MsgBox "Please select an UV Analysis Method before proceeding."
        Exit Sub
    End If
    
    Dim querywb As Workbook
    Set querywb = Workbooks.Open(Filename:="https://dtxpharma.sharepoint.com/:x:/s/Chemistry/EZxDgGlrMDlIvqQ9BP0sy64BybrMtMzXGByS-HNMCblVaA?e=Hn4Haq", ReadOnly:=True, UpdateLinks:=False)
    querywb.Windows(1).Visible = False

    Dim headers As Variant
    
    headers = Array("Vol_Req", "Unit of Vol_Req", "Conc_Req", "Unit of Conc_Req", "Study Type", "Convert Vol Unit?", _
        "Standardized Vol + DispExtra", "Standardized Conc (uM)", "umol requested", "Amount to Retain", "Auto DF", _
        "Theo Abs AutoDF", "Chosen DF", "Theo Abs of Chosen DF", _
        "DF QC Volume (uL)", "Vol for 6 QC", "Vol to Prep (uL)", "umol in prep", "mg (UV) in prep", "multiple preps?", "min umol req'd (stock)", _
        "mg (UV) in stock", "UV/dry mass ratio", "adj factor (inverse of ratio)", "total mg to weigh(single_lineitem)", "total mg to weigh (grouped)", "Protic MW", "Ex Co", "Target", "Requested Volume", "Requested Concentration")
    
    Dim i As Integer
    For i = 0 To UBound(headers)
        Range("K11").Offset(0, i).value = headers(i)
    Next i
    
    ' Set the row height for row 11 to 30
    Rows(11).RowHeight = 45
    Rows(11).WrapText = True
    Rows(11).HorizontalAlignment = xlCenter
    Rows(11).VerticalAlignment = xlVAlignTop
    
    Range("G12").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.TextToColumns Destination:=Range("K12"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=True, Other:=True, OtherChar:= _
        "@", FieldInfo:=Array(Array(1, 1), Array(2, 2), Array(3, 1), Array(4, 2)), _
        TrailingMinusNumbers:=True
        
    
    Set sheettbl = ActiveSheet.ListObjects(1) ' Assumes the active table is the first table on the sheet.
    
    Set formulaColumn = sheettbl.ListColumns(37).DataBodyRange  'Column AK - Protic MW Query
    formulaColumn.Formula = "=VLOOKUP($A12,'https://dtxpharma.sharepoint.com/sites/Chemistry/Shared Documents/Oligo Manufacturing - Research/AS/Documents/Database Excels/DTx References/[2023Query.xlsx]GenConstructQuery'!$A$2:$D$16000,4,FALSE)"
    
    Set formulaColumn = sheettbl.ListColumns(38).DataBodyRange  'Column AL - Ex Co Query
    formulaColumn.Formula = "=VLOOKUP($A12,'https://dtxpharma.sharepoint.com/sites/Chemistry/Shared Documents/Oligo Manufacturing - Research/AS/Documents/Database Excels/DTx References/[2023Query.xlsx]GenConstructQuery'!$A$2:$E$16000,5,FALSE)"
    
    Set formulaColumn = sheettbl.ListColumns(39).DataBodyRange  'Column AM - Target Query
    formulaColumn.Formula = "=VLOOKUP($A12,'https://dtxpharma.sharepoint.com/sites/Chemistry/Shared Documents/Oligo Manufacturing - Research/AS/Documents/Database Excels/DTx References/[2023Query.xlsx]Formulations'!$A$2:$C$16000,2,FALSE)"
    Set formulaColumn = sheettbl.ListColumns(15).DataBodyRange ' Assumes the formula will be added to the fifteenth column.
    formulaColumn.Formula = "=IF(([@[Unit of Conc_Req]])=""mg/mL"", ""in vivo"", IF(([@[Unit of Conc_Req]])=""uM"",""in vitro"", """"))"
    
    Set formulaColumn = sheettbl.ListColumns(16).DataBodyRange ' Assumes the formula will be added to the 16th column (P).
    formulaColumn.Formula = "=IF(([@[Unit of Vol_Req]])=""uL"", ""N"", ""Y"")"

    Set formulaColumn = sheettbl.ListColumns(17).DataBodyRange  'Column Q - Standardized Vol + Extra
    formulaColumn.Formula = "=IF(([@[Unit of Vol_Req]]=""uL""), [@[Vol_Req]]+10, IF(([@[Unit of Vol_Req]]=""mL""), ([@[Vol_Req]]*1000)+100,  IF(([@[Unit of Vol_Req]]=""L""), ([@[Vol_Req]]*10^6)+1000,"""")))"
    
    Set formulaColumn = sheettbl.ListColumns(18).DataBodyRange  'Column R - Standardized conc (uM)
    formulaColumn.Formula = "=IF(([@[Unit of Conc_Req]])=""mg/mL"", [@[Conc_Req]]/[@[Protic MW]]*10^6, IF(([@[Unit of Conc_Req]])=""uM"",[@[Conc_Req]], """"))"
    
    Set formulaColumn = sheettbl.ListColumns(19).DataBodyRange  'Column S - umol requested
    formulaColumn.Formula = "=[@[Standardized Conc (uM)]]*[@[Standardized Vol + DispExtra]]/10^6"
    
......

    querywb.Close SaveChanges:=False
    
    ws.OLEObjects("optPlate").Visible = False
    ws.OLEObjects("optPlate").Visible = True
    ws.OLEObjects("optCell").Visible = False
    ws.OLEObjects("optCell").Visible = True
    
    ' Turn on screen updating
    Application.ScreenUpdating = True

    ' Force Excel to complete any pending calculations
    Application.Calculate
    
    Dim tbl As ListObject
    Set ws = ActiveSheet
    Set tbl = ws.ListObjects(1)
    
    tbl.Sort.SortFields.Clear

    tbl.Sort.SortFields.Add2 Key:=tbl.ListColumns("Requested Lot").DataBodyRange, _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

    tbl.Sort.SortFields.Add2 Key:=tbl.ListColumns("Standardized Conc (uM)").DataBodyRange, _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal

    With tbl.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .Apply
    End With

End Sub
 
Upvote 0

Forum statistics

Threads
1,223,883
Messages
6,175,168
Members
452,615
Latest member
bogeys2birdies

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top