2012-10-02 166 views
0

下面是表的樣品(有令人毛骨悚然的樣本數據)MS Excel的VBA宏動態範圍

|Col A  |Col B  |Col C |Col D  |Col E 
+------------+----------+--------+----------+----- 
|Number  |Value  |X  |Date  |Decimal 
|1   |  AA|X  |2012/01/01|.1 
|2   |  BB|X  |2012/02/01|.2 
|3   |  CC|X  |2012/03/01|.3 
|4   |  DD|X  |2012/04/01|.4 
|5   |  EE|X  |2012/05/01|.5

需要採取哪些措施:

  • 排序表根據「值」 (在這種情況下色柱B)在一個宏

條件:

  • 標題值不會改變
  • 我必須搜索包含單詞「Value」的標題,因爲它從Col C變爲Col D或Col A ... B ... E ...
  • 列標題總是停留在第一排

我迄今所做的:

  • 蠻力價值的...
  • 搜索標題中查找列包含(BAD!)標題「值」
  • 獲取變量

問題列字母/數字和存儲:

  • 使用列字母或數字作爲排序依據。 (即範圍(colLetter & 「:」 & colLetter))

任何幫助將appriciated

回答

0
Sub Tester() 

Const SORT_HEADER As String = "Value" 
Dim sht As Worksheet, f As Range 


    Set sht = Worksheets("Sheet1") 

    Set f = sht.Rows(1).Find(SORT_HEADER, LookIn:=xlValues, lookat:=xlWhole) 

    If Not f Is Nothing Then 

     sht.Range("A1").CurrentRegion.Sort _ 
      Key1:=sht.Columns(f.Column), Order1:=xlAscending, Header:=xlYes 

    Else 
     MsgBox "'" & SORT_HEADER & "' column not found!" 
    End If 

End Sub