VBA将细胞/细胞范围传递给多个亚细胞

时间:2016-01-20 20:27:49

标签: excel vba excel-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

从未真正使用excel宏在VBA中工作,所以我对此非常新,所以任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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