我创建了这个函数来根据单元格值隐藏一些行。
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
当单位价值不是" XXX"函数工作正常,但当它是" XXX"时,调用此函数的单元格变为#VALUE!
答案 0 :(得分:1)
如果您关心返回现在是否隐藏了单元格,那么您可以将其保留为函数。否则将其设为Sub并删除下面的myTest = ...
行。在VBA中选择单元格几乎总是一个糟糕的主意。这是不可靠的,越野车和巨大的减速。以下代码是我可以为您提供的最简洁的功能。它直接将Unit = "XXX"
的True / False评估应用于行的Hidden属性。我添加了一个显式的布尔返回类型。
Function myTest(Unit As String) As Boolean
ThisWorkbook.Worksheets("Sheet5").Rows("15:16").EntireRow.Hidden = (Unit = "XXX")
myTest = Not (Unit = "XXX")
End Function
为了更接近您的结构,您可以使用范围对象:
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
或者您可以使用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