隐藏给定行数的Excel宏

时间:2017-05-26 08:37:42

标签: excel vba excel-vba

我正在寻找关于这个问题的答案,但没有运气。 我想要一个excel宏来根据单元格值隐藏行。 我的表位于第18行和第418行之间,请您查看我的VBA代码:

Sub HideRows()

Dim np As Integer

np = Range("W1").Value
'hidding all the table rows first                
ActiveSheet.Rows("18:418").EntireRow.Hidden = True
'showing only from row 18 to the number given by cell "W1"
ActiveSheet.Rows("18:np").EntireRow.Hidden = False

End Sub

它给我一个类型不匹配的错误,有没有办法让这个工作?非常感谢你

2 个答案:

答案 0 :(得分:3)

更改

ActiveSheet.Rows("18:np").EntireRow.Hidden = False

ActiveSheet.Rows("18:" & np).EntireRow.Hidden = False

答案 1 :(得分:0)

放手一搏

Sub HideRows()

Dim np As Long

    np = Range("W1").Row
    'hidding all the table rows first                
    ActiveSheet.Range("18:418").EntireRow.Hidden = True
    'showing only from row 18 to the number given by cell "W1"
    ActiveSheet.Range("18:np").EntireRow.Hidden = False

End Sub

此外,Dim大多数数字最好Long而不是IntegerLong具有更长的字符大小(即,您可以使用更大的数字,其中整数的最大值为±32767)如果您循环浏览大型数据集,则值得注意。此外,VBA在32位环境中对它们完全相同 - 当它编译时,它会转换Integer's to Long`。 Int & Long Reference