2016-01-20 168 views
3

嗨,我有一個問題,定義一個單元格的範圍作爲一個變量,取決於什麼樣的細胞組發生了變化。到目前爲止,我有這個,但它發送了多個錯誤,我試着將它們作爲字符串傳遞並創建臨時變量來保存值並傳遞它,但不管它看起來沒有工作。VBA將細胞/細胞的範圍傳遞給多個潛艇

Private Sub Worksheet_Change(ByVal Target As Range) 
If Not (Application.Intersect(Worksheets("Sheet1").Range("A:E"), Target) Is Nothing) Then 
    DoSort("A3:F100", "A4") 
End If 
If Not (Application.Intersect(Worksheets("Sheet1").Range("H:L"), Target) Is Nothing) Then 
    DoSort("H3:M100", "H4) 
End If 
End Sub 

Sub DoSort(x As Range, y As Range) 
With ThisWorkbook.Sheets("Sheet1") 
.Range(x).Sort Key1:=.Range(y), Order1:=xlAscending, Header:=xlYes 
End With 
End Sub 

我有,當我硬編碼的細胞像在此之前的工作:

Private Sub DoSort2() 
With ThisWorkbook.Sheets("Sheet1") 
.Range("H3:M100").Sort Key1:=.Range("H4"), Order1:=xlAscending, Header:=xlYes 
End With 
End Sub 

從來沒有真正工作在VBA與Excel宏所以很新的這一點,所以任何幫助,將不勝感激!

回答

3

請參閱下面的重構代碼。請參閱我的評論以獲取解釋

Private Sub Worksheet_Change(ByVal Target As Range) 

    'I used "Me." in place of "Worksheets("Sheet1")." assuming that the Worksheet_Change event is already on Sheet1  
    If Not Intersect(Me.Range("A:E"), Target) Is Nothing Then 
     DoSort "A3:F100", "A4" 
    End If 

    If Not Intersect(Me.Range("H:L"), Target) Is Nothing Then 
     DoSort "H3:M100", "H4" 'you were missing a close " here 
    End If 

End Sub 

'define x and y as String to pass the string address of the range reference 
Sub DoSort(x As String, y As String) 
    With ThisWorkbook.Sheets("Sheet1") 
     .Range(x).Sort Key1:=.Range(y), Order1:=xlAscending, Header:=xlYes 
    End With 
End Sub 

如果您願意,也可以通過該範圍。這將是這樣的:

DoSort Me.Range("A3:F100"), Me.Range("A4") 

    Sub DoSort(x as Range, y as Range) 
     x.Sort Key1:=y, Order1:=xlAscending, Header:=xlYes 
    End Sub 
+0

聰明的我指針(則要remeber說),我也得到某種方式得到來自代碼的語法錯誤。有什麼我失蹤?我還必須在sub中定義x和y,因爲它們在傳遞引用時已經聲明瞭嗎? – Phoenix1237

+1

@ Phoenix1237 - 語法錯誤發生在哪一行?並且不需要在「DoSort」子文件中定義'x'或'y'。參數引用已經做到了。 –

+0

Sub Worksheet_Change(ByVal Target As Range)發生錯誤,但該宏存儲在Sheet1中。 – Phoenix1237

0

你可以作爲一個字符串傳遞數據對比爲一個範圍:使用

Private Sub Worksheet_Change(ByVal Target As Range) 
    If Not (Application.Intersect(Worksheets("Sheet1").Range("A:E"), Target) Is Nothing) Then 
     DoSort("A3:F100", "A4") 
    End If 
    If Not (Application.Intersect(Worksheets("Sheet1").Range("H:L"), Target) Is Nothing) Then 
     DoSort("H3:M100", "H4") 
    End If 
End Sub 

Sub DoSort(x As String, y As String) 
    With ThisWorkbook.Sheets("Sheet1") 
     .Range(x).Sort Key1:=.Range(y), Order1:=xlAscending, Header:=xlYes 
    End With 
End Sub 
+0

是的,我試過這個,但當我嘗試測試時,我以某種方式得到語法錯誤。 – Phoenix1237

+0

@ Phoenix1237哪一行是錯誤? – Chrismas007

+0

它指向Private Sub Worksheet_Change(作爲範圍的ByVal目標) – Phoenix1237