简体   繁体   中英

VBA Help: Setting up an auto running VBA with a dynamic range

So the data i have is in this format: Stock Data

The '31-Mar-18' is a manual input and when a date is input there, i am trying to have a function run which would sort in descending order the corresponding column that has the same header as the input data cell. So for example if the input cell is '31-Mar-18', then the data should be sorted based on descending order of values in the column with '31-Mar-18' as the header.

I was playing around with this code but given my limited knowledge not sure how to proceed. Any input would be much appreciated.

Sub SortDataWithHeader()
Range("DataRange").Sort Key1:=Range("B15"), Order1:=xlDescending

End Sub

It seems that you have misunderstood the usage of the key1 property. Refer to this link for more details. key1 should contain all values to be sorted (eg in a range object) and not the column name.

the following could potentially be useful to you, but you need to adjust cells references accordingly and add error catching where it makes sense.

What the code is that it looks for the date that you have in cell B15 and tries to find the cell that holds it in the row 17. Then it takes that cell and extends it to the end so it defines the cells to be sorted. It uses the autofilter.sort instead of the range.sort because from what i can see in your posted image you already have the autofilter applied.

Option Explicit

Public Sub sSort()

  Dim headerColumn As Range, headers As Range, foundRange As Range, sortItems As Range
  Dim headerColumnNumber As Long
  Dim lookupValue As Variant

  lookupValue = Sheet1.Range("B15").Value
  Set headers = Sheet1.Range("17:17")
  Set foundRange = headers.Find(lookupValue, LookIn:=xlValues)

  Set sortItems = Range(foundRange.Offset(1, 0), foundRange.End(xlDown))

  Sheet1.AutoFilter.Sort.SortFields.Clear
  Sheet1.AutoFilter.Sort.SortFields.Add Key:=sortItems, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

  With Sheet1.AutoFilter.Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
  End With

End Sub

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