Excel VBA宏工作表\u更改无法正常工作
我有一个正常运行的宏问题。我编写了一个简短的代码来隐藏或取消隐藏最后两列,具体取决于所选月份 可以使用组合框选择月份。每个月都为其分配一个编号(1-1月、2-2月等)。数字显示在单元格A1中,并在选择一个月后发生变化 我希望宏根据我选择的月数正常运行Excel VBA宏工作表\u更改无法正常工作,excel,vba,Excel,Vba,我有一个正常运行的宏问题。我编写了一个简短的代码来隐藏或取消隐藏最后两列,具体取决于所选月份 可以使用组合框选择月份。每个月都为其分配一个编号(1-1月、2-2月等)。数字显示在单元格A1中,并在选择一个月后发生变化 我希望宏根据我选择的月数正常运行 Private子工作表\u更改(ByVal目标作为范围) 暗nr_kol与长 如果Target.Address=“$A$1”,则 对于nr_kol=32至34 如果月份(单元格(6,nr_kol))=单元格(1,1),则 列(nr_kol).Hid
Private子工作表\u更改(ByVal目标作为范围)
暗nr_kol与长
如果Target.Address=“$A$1”,则
对于nr_kol=32至34
如果月份(单元格(6,nr_kol))=单元格(1,1),则
列(nr_kol).Hidden=False
其他的
列(nr_kol).Hidden=True
如果结束
下一个
如果结束
端接头
编辑(抱歉,单击提交太快)
单元格A1根据组合框的选择而变化(框位于不同的行中)。我注意到的是,列将隐藏,但只有在手动更改单元格A1时才会隐藏。但是,当我将单元格更改为包含30或31天的月份索引时,列将保持隐藏,因此我有两个问题
下图及其说明
Option Explicit
Dim monthsList(11) As String
Dim firstCell As Integer
Dim lastCell As Integer
Private Sub ComboBox1_Change()
Columns("A:XX").Hidden = False
'0 to reset the columns
If ComboBox1.Value = 0 Then Exit Sub
'take the last month of the list
Dim var1() As String
var1 = Split(monthsList(11), "~")
firstCell = 4 'assuming that the start of the date begins from column 4
lastCell = Val(var1(2))
Range(Cells(firstCell, firstCell), Cells(firstCell, lastCell)).EntireColumn.Hidden = True
Erase var1
var1 = Split(monthsList(ComboBox1.Value - 1), "~")
firstCell = Val(var1(1))
lastCell = Val(var1(2))
'display only current selected month
Range(Cells(firstCell, firstCell), Cells(firstCell, lastCell)).EntireColumn.Hidden = False
End Sub
Private Sub Worksheet_Activate()
Erase monthsList
'unhide any columns or write a macro that recognises the hidden columns and keeps it hidden
Columns("A:XX").Hidden = False
Dim i As Integer
ComboBox1.Clear
For i = 0 To 12
ComboBox1.AddItem i
Next
'0 added to display all the sheets
ComboBox1.Select (1)
'let this be the start of the date range
'select the cell in the second row
Range("D2").Select
'go to the last date
Selection.End(xlToRight).Select
'go to the first row
ActiveCell.Offset(-1, 0).Select
lastCell = ActiveCell.Column
'select the last month
Selection.End(xlToLeft).Select
For i = 12 To 1 Step -1
'cell value start date of the month last date of the month
monthsList(i - 1) = ActiveCell.Value & "~" & ActiveCell.Column & "~" & lastCell
lastCell = ActiveCell.Column - 1
Selection.End(xlToLeft).Select
Next
End Sub
请注意,您需要根据需要进行必要的更改
我希望这能解决你的痛苦
请将其标记为答案将您的(调整后的)隐藏代码放入下拉列表中,而不是工作表更改事件中