VBA将细胞/细胞的范围传递给多个潜艇

您好我有一个问题定义一个单元格的范围作为一个variables,取决于什么样的一组单元已经改变。 到目前为止,我有这个,但它发送了多个错误,我曾尝试将它们作为string传递,并创build临时variables来保存值,并传递,但不pipe它似乎没有工作。

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 

从来没有真正的工作与Excelmacros的VBA所以这是非常新的,所以任何帮助将不胜感激!

看到我下面重构的代码。 看到我的意见的解释。

 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 

您可以将数据作为string传递给范围:

 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