我按照链接视频文字中的说明进行操作。我练习遵循,因为我试图将相同的方法应用到我的工作簿中。
我的单元格 B1 中有一个下拉列表,其中列出了以下选项:
“现金支付”数据集位于 D 至 H 列中 “借记卡付款”数据集位于 J 至 N 列中 “信用卡付款”数据集位于 P 至 T 列中
但是,当我粘贴代码(见下文)并从单元格 B1 的列表中选择“现金付款、借记卡付款或信用卡付款”时,从 D 开始的所有列都不会显示。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim PayType As Range
Set PayType = Range("B1")
If Intersect(Target, PayType) Is Nothing Then Exit Sub
'add as many data sets as required
Dim Rng1 As Range
Dim Rng2 As Range
Dim Rng3 As Range
'add as many headings as you require
Dim FindHdg1 As Range
Dim FindHdg2 As Range
Dim FindHdg3 As Range
'put your headings in the brackets
Set FindHdg1 = Cells.Find("Cash Payments")
Set FindHdg2 = Cells.Find("Debit Card Payments")
Set FindHdg3 = Cells.Find("Credit Card Payments")
Dim ColsToHide As Range
Set ColsToHide = Range("D1:XFD1")
If Intersect(Target, PayType) Is Nothing Then Exit Sub
'add a case for each option in your drop-down & and add more if required
Select Case PayType
Case Is = "All"
Cells.EntireColumn.Hidden = False
Case Is = "Cash Payments"
Cells.EntireColumn.Hidden = False
Set Rng1 = FindHdg1.CurrentRegion
ColsToHide.EntireColumn.Hidden = True
Rng1.EntireColumn.Hidden = False
Case Is = "Debit Card Payments"
Cells.EntireColumn.Hidden = False
Set Rng2 = FindHdg2.CurrentRegion
ColsToHide.EntireColumn.Hidden = True
Rng2.EntireColumn.Hidden = False
Case Is = "Credit Card Payments"
Cells.EntireColumn.Hidden = False
Set Rng3 = FindHdg3.CurrentRegion
ColsToHide.EntireColumn.Hidden = True
Rng3.EntireColumn.Hidden = False
End Select
End Sub
修改这部分代码
Set FindHdg1 = Cells.Find("Cash Payments", Range("B1"))
Set FindHdg2 = Cells.Find("Debit Card Payments", Range("B1"))
Set FindHdg3 = Cells.Find("Credit Card Payments", Range("B1"))
这是必要的,因为在原始代码中搜索从单元格 A1 开始,并且总是找到单元格 B1 而不是您需要的单元格。使用 mod,
Find
方法将在单元格 B1 之后启动,并返回所需的结果。