簡體   English   中英

VBA 幫助:設置具有動態范圍的自動運行 VBA

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

所以我擁有的數據是這種格式:股票數據

'31-Mar-18' 是手動輸入,當在那里輸入日期時,我正在嘗試運行 function ,它將按降序排列與輸入數據單元格具有相同 header 的相應列。 因此,例如,如果輸入單元格是“18 年 3 月 31 日”,則應根據“18 年 3 月 1 日”列中值的降序對數據進行排序,即 header。

我在玩這段代碼,但鑒於我的知識有限,不知道如何繼續。 任何輸入將不勝感激。

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

End Sub

看來您誤解了 key1 屬性的用法。 有關更多詳細信息,請參閱此鏈接 key1 應該包含所有要排序的值(例如在范圍對象中),而不是列名。

以下內容可能對您有用,但您需要相應地調整單元格引用並在有意義的地方添加錯誤捕獲。

代碼是什么,它在單元格 B15 中查找您擁有的日期,並嘗試在第 17 行中找到包含它的單元格。然后它獲取該單元格並將其擴展到末尾,以便定義要排序的單元格。 它使用 autofilter.sort 而不是 range.sort,因為從我在您發布的圖像中看到的內容,您已經應用了自動過濾器。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM