好吧我正在尝试在excel中创建一个Show Hide按钮,这是一个大文档,所以我不想为每个按钮创建一个新的sub,每个按钮都有一个新的范围,我理想地想要它离开按钮的位置,我想显示/隐藏按钮下方的10行。我找到了一个连接我的'Show'子和我的'Hide'子的子,所以我只需要使用一个按钮,但这是我到目前为止所拥有的:
Sub Hide()
Dim addr As Object, rs As Long, cs As Long
'addr is the address of the button
'rs is the row number
'cs is the column number
Dim offset1 As Long
'offset for rows value
Dim offset2 As Long
'offset 2 for row value
Dim rs1 As Long
Dim rs2 As Long
Dim rng As Range
Dim sheet As Worksheet
'rng is the cell the button is in
Set sheet = Worksheets("Sheet1")
Set addr = sheet.Shapes(Application.Caller)
'address of the shape using the macro (i.e. the button)
With addr.TopLeftCell
'coordinates of the top left cell of the button
rs = .Row
'row number
cs = .Column
'column number
End With
offset1 = -1
offset2 = -10
rs1 = rs + offset1
rs2 = rs + offset2
With sheet
.Cells(rs1 & ", " & cs).Select
Set rng = .Range(.Cells(rs1 & "," & cs), .Cells(rs2 & "," & cs))
End With
' let rng be the cell the button is in
rng.EntireRow.Hidden = True
End Sub
我使用.offset和.resize函数为我的第一个按钮工作但是当我在另一个位置尝试它时,如果没有完全改变偏移,它就无法工作。
提前致谢
答案 0 :(得分:0)
问题在于您使用Cells
。如果给它两个整数,它们是两个独立的参数而不是连接的。变化
.Cells(rs1 & ", " & cs).Select
Set rng = .Range(.Cells(rs1 & "," & cs), .Cells(rs2 & "," & cs))
到
.Cells(rs1, cs).Select
Set rng = .Range(.Cells(rs1, cs), .Cells(rs2, cs))
答案 1 :(得分:0)
Cells()
将2(或1)Long
个参数作为参数。您改为:Cells(rs1 & "," & cs)
,这不是一个正确的参数。
尝试执行以下操作:
With Sheet
.Cells(rs1, cs).Select
Set Rng = .Range(.Cells(rs1 & "," & cs), .Cells(rs2 & "," & cs))
End With
如果您阅读How to avoid using Select in Excel VBA,则可以将代码更改为:
With Sheet
.Range(.Cells(rs1, cs), .Cells(rs2, cs)).EntireRow.Hidden = True
End With
因此,避免Select
并编写更少的代码。
答案 2 :(得分:-1)
在我看来,你过于复杂了。
有两个主要问题。
例如
我们可以看到按钮大致在第8行结束。所以我们可以隐藏10到20行(或任何你想要的)。
使用以下代码进行切换:
Private Sub hide_button_Click()
If (Rows("10:20").EntireRow.Hidden = True) Then
Rows("10:20").EntireRow.Hidden = False
Else
Rows("10:20").EntireRow.Hidden = True
End If
End Sub
编辑:在你的问题中,你说你想要使用10行,所以我把它变成一个静态值,显然如果你正在使用动态范围,将间隔10:20更改为任何变量您已存储数据的起始和结束范围