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!
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. Selecting cells in VBA is almost always an awful idea. 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. 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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.