我不确定为什么我的代码无效。它旨在识别我何时按下按钮(说“Hide1”)并逐行搜索每列,查找值为1
的单元格一旦执行此操作,它应该更改按钮说“显示1”。但是,当我运行它时,根本没有任何反应。
以下是Excel的宏:
Sub Hide_columns()
Dim i As Integer
Dim j As Integer
i = 3
j = 4
Do Until i = 26
Do Until j = 54
With ActiveSheet.Cells(i, j)
If .Value = 1 Then
ActiveSheet.Columns(i).EntireColumn.Hidden = True
With ActiveSheet.Shapes(Application.Caller).TextFrame.Characters
If .Text = "Show 1" Then
.Text = "Hide 1"
ElseIf .Text = "Hide 1" Then
.Text = "Show 1"
Else
MsgBox ("VBA has gone wrong.")
Exit Sub
End If
End With
End If
End With
j = j + 1
Loop
i = i + 1
Loop
End Sub
答案 0 :(得分:1)
你必须重新构建内循环:
Sub Hide_columns()
Dim i As Integer
Dim j As Integer
i = 3
Do Until i = 26
j = 4
Do Until j = 54
With ActiveSheet.Cells(i, j)
If .Value = 1 Then
MsgBox i & vbCrLf & j
ActiveSheet.Columns(i).EntireColumn.Hidden = True
With ActiveSheet.Shapes(Application.Caller).TextFrame.Characters
If .Text = "Show 1" Then
.Text = "Hide 1"
ElseIf .Text = "Hide 1" Then
.Text = "Show 1"
Else
MsgBox ("VBA has gone wrong.")
Exit Sub
End If
End With
End If
End With
j = j + 1
Loop
i = i + 1
Loop
End Sub
说明:第一次通过外循环(对于A列),行号j
从4开始循环直到它54.但第二次通过外循环(对于B列),j
仍然停留在54,因此不会检查B列中的任何行。要解决此问题,请在每次移动到新列时将j
重置为4,如上所示。