做过项目管理或者产品管理的小伙伴或多或少都会对Excel比较依赖,那么你了解过什么是VBA吗?
复杂场景下对Excel的高级应用可能需要借助VBA代码才能实现。有些小伙伴可能了解VBA,有些可能还没接触过。今天我给大家讲一个复杂场景下通过VBA实现Excel模块筛选的高级应用。
这里我们先通过图片和文字描述一下需要实现的一个需求场景:
首先有一个Excel,其中有两个Sheet,Sheet1是所有模块的汇总表,Sheet2是通过Sheet1整理出来所有模块的事件处理。
要求点击Sheet2中模块列中某一项,可以动态跳转到Sheet1中且需要实现对Sheet1进行对应模块项的筛选。
附带Sheet1如图:
附带Sheet2如图:
点击Sheet2中模块列的某一项,例如‘A1模块’,需要动态跳转到Sheet1中且需要实现对Sheet1进行‘A1模块’的筛选。
跳转Sheet1且展示的效果:
就是这样的一个需求场景。我这里采用VBA代码实现,如下。
Dim tempAddressValue As String
Dim tempAddressReplaceValue As String
Dim tempAddressSplitValue As String
Dim moreTypeValue As String
Dim singleTypeValue As String
Dim matchMoreTypeValue As String
Dim matchSingleTypeValue As String
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
tempAddressValue = ""
tempAddressReplaceValue = ""
tempAddressSplitValue = ""
moreTypeValue = ""
singleTypeValue = ""
matchSingleTypeValue = ""
matchMoreTypeValue = ""
If Target.MergeCells = True Then
tempAddressValue = Target.Address
tempAddressReplaceValue = Replace(tempAddressValue, "$", "")
tempAddressSplitValue = Split(tempAddressReplaceValue, ":")(0)
moreTypeValue = Range(tempAddressSplitValue).Value
If moreTypeValue = "A4模块" Then
matchMoreTypeValue = "=*" + moreTypeValue + "*"
Sheets("汇总").Select
ActiveSheet.ListObjects("表1").Range.AutoFilter Field:=3, Criteria1:= _
matchMoreTypeValue, Operator:=xlAnd
Else
End If
Else
singleTypeValue = Target.Value
If singleTypeValue = "A1模块" Or singleTypeValue = "A2模块" Or singleTypeValue = "A3模块" Or singleTypeValue = "A5模块" Or singleTypeValue = "A6模块" Or singleTypeValue = "A7模块" Or singleTypeValue = "A8模块" Or singleTypeValue = "B1模块" Or singleTypeValue = "B2模块" Or singleTypeValue = "B3模块" Or singleTypeValue = "C1模块" Or singleTypeValue = "C2模块" Or singleTypeValue = "C3模块" Then
matchSingleTypeValue = "=*" + singleTypeValue + "*"
Sheets("汇总").Select
ActiveSheet.ListObjects("表1").Range.AutoFilter Field:=3, Criteria1:= _
matchSingleTypeValue, Operator:=xlAnd
Else
End If
End If
End Sub
vbnet
特别提示:
含有VBA代码的Excel,打开时候是需要开启‘宏’。有些VBA代码不同Excel版本略有差异。当然上面的VBA代码还有待很多优化的部分,考虑到大家对VBA了解程度不同,我这里就很简单的实现了。
以上代码仅供参考,如有不当之处,欢迎指出!!!
更多干货,欢迎大家关注和联系我。期待和大家一起更好的交流、探讨技术!!!