如何组合两个vba代码?

时间:2017-07-28 10:00:37

标签: excel vba excel-vba

我想在一张纸上合并(运行)两个不同的vba功能。怎么做?

Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice 20161123
    Dim rgTable As Range
    Dim rgData As Range
    Dim xColumn As Integer
    On Error Resume Next
    Application.ScreenUpdating = False
    Set rgTable = Range("mydata")
    With rgTable
        Set rgData = .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count)
        If Not Application.Intersect(ActiveCell, rgData.Cells) Is Nothing Then
            xColumn = ActiveCell.Column - .Column + 1
            If ActiveSheet.AutoFilterMode = False Then
                .AutoFilter
            End If
            If ActiveSheet.AutoFilter.Filters(xColumn).On = True Then
                .AutoFilter Field:=xColumn
            Else
                .AutoFilter Field:=xColumn, Criteria1:=ActiveCell.Value
            End If
        End If
    End With
    Set rgData = Nothing
    Set rgTable = Nothing
    Application.ScreenUpdating = True
End Sub

Public blnToggle As Boolean
Private Sub Worksheet_BeforeDoubleClick _
    (ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice 20161123
    Dim LastColumn As Long, keyColumn As Long, LastRow As Long
    Dim SortRange As Range
    LastColumn = _
    Cells.Find(What:="*", After:=Range("A1"), _
    SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    keyColumn = Target.Column
    If keyColumn > LastColumn Then Exit Sub
    Application.ScreenUpdating = False
    Cancel = True
    LastRow = Cells(Rows.Count, keyColumn).End(xlUp).Row
    Set SortRange = Target.CurrentRegion
    blnToggle = Not blnToggle
    If blnToggle = True Then
        SortRange.Sort _
        Key1:=Cells(2, keyColumn), Order1:=xlAscending, Header:=xlYes
    Else
        SortRange.Sort _
        Key1:=Cells(2, keyColumn), Order1:=xlDescending, Header:=xlYes
    End If
    Set SortRange = Nothing
    Application.ScreenUpdating = True
End Sub

来源: https://www.extendoffice.com/documents/excel/4258-excel-click-cell-to-filter.html https://www.extendoffice.com/documents/excel/4259-excel-click-on-header-to-sort.html

1 个答案:

答案 0 :(得分:1)

这就是你将两个功能合二为一的方法。想象一下,您有Code1Code2,并且想要建立Code1AndCode2Together

Public Sub Code1()
    Debug.Print "I am code 1"
End Sub

Public Sub Code2()
    Debug.Print "I am code 2"
End Sub

您应该做的是检查这些代码正在做什么并将它们联合起来。一般来说,它应该是这样的:

Public Sub Code1AndCode2Together()
    Debug.Print "I am code 1"
    Debug.Print "I am code 2"
End Sub

或者像这样:

Public Sub Code1AndCode2Together()
    Code1
    Code2
End Sub

在你的情况下 - 简单地复制和粘贴可能不会起作用,但它是一个良好的开端。然后尝试理解代码正在做什么并尝试实现它。