[英]How to create a function to hide rows based on a cell value in VBA EXCEL
I created this function to hide some rows based on a cell value. 我创建了此函数以根据单元格值隐藏一些行。
Function myTest(Unit As String)
ThisWorkbook.Worksheets("TESTING").Rows("15:16").Select
If Unit = "XXX" Then
Selection.EntireRow.Hidden = True
Else
Selection.EntireRow.Hidden = False
myTest= "1"
End If
End Function
When the unit value is not "XXX" the functions works fine, but when it is "XXX", the cell that calls this function gets #VALUE! 当单位值不是“ XXX”时,功能可以正常工作,但是当单位值为“ XXX”时,调用此功能的单元格将获得#VALUE!
If you care about returning whether the cells are now hidden, then you can keep it as a function. 如果您关心返回现在是否隐藏了单元格,则可以将其保留为函数。 Otherwise make it a Sub and get rid of the
myTest = ...
line below. 否则,使其成为Sub并摆脱下面的
myTest = ...
行。 Selecting cells in VBA is almost always an awful idea. 在VBA中选择单元几乎总是一个糟糕的主意。 It is unreliable, buggy, and a huge slowdown.
这是不可靠的,有故障的,并且速度非常慢。 The following code is the most concise function I can give you to do this.
以下代码是我可以为您提供的最简洁的功能。 It directly applies the True/False evaluation of
Unit = "XXX"
to the Hidden property of the rows. 它将
Unit = "XXX"
的True / False评估直接应用于行的Hidden属性。 I added an explicit Boolean return type. 我添加了一个明确的布尔返回类型。
Function myTest(Unit As String) As Boolean
ThisWorkbook.Worksheets("Sheet5").Rows("15:16").EntireRow.Hidden = (Unit = "XXX")
myTest = Not (Unit = "XXX")
End Function
To stay closer to your structure you could use a range object: 为了更接近您的结构,您可以使用范围对象:
Function myTest(Unit As String) As String
Dim rng As Range
rng = ThisWorkbook.Worksheets("TESTING").Rows("15:16")
If Unit = "XXX" Then
rng.EntireRow.Hidden = True
myTest = "0"
Else
rng.EntireRow.Hidden = False
myTest= "1"
End If
End Function
Or you could use a With block: 或者,您可以使用With块:
Function myTest(Unit As String) As String
With ThisWorkbook.Worksheets("TESTING").Rows("15:16")
If Unit = "XXX" Then
.EntireRow.Hidden = True
myTest = "0"
Else
.EntireRow.Hidden = False
myTest= "1"
End If
End With
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.