我在我的过程中使用if语句来调用我的Boolean函数;但是,当我运行程序时,它总是输出消息,就好像函数是真的一样。
Public Function INR() As Boolean
If Avg < 1.5 & SD < 0.5 Then
INR = True
Else
INR = False
End If
End Function
Public Sub PatientINR()
Range("B2", Range("B1").End(xlDown)).Name = "Name"
Dim cell As Range, reply As String, i As Long, x As Variant, Avg As Long, SD As Long
reply = InputBox("Enter patient's name", "INR", "Madelyn Carberry")
i = 1
x = Range("Name").Cells(i)
Do Until x = reply
i = i + 1
x = Range("Name").Cells(i)
Loop
Avg = Range("Name").Cells(i, 17)
SD = Range("Name").Cells(i, 18)
Call INR
If INR = True Then
MsgBox reply & "'s INR record is satisfactory for the procedure"
End If
If INR = False Then
MsgBox reply & "'s INR record is not satisfactory for the procedure"
End If
End Sub
答案 0 :(得分:2)
您需要将数据传递给该函数。将函数的第一行更改为:
Public Function INR(Avg As Double, SD As Double) As Boolean
然后当你调用函数时传递变量:
If INR(Avg,SD) Then
原样,值未传递,因此在测试时为0。这将返回真实。
如上所示,您不需要= True
它是一个布尔值,因此已经是真或假。
也不要测试False只使用Else:
If INR(Avg,SD) Then
MsgBox reply & "'s INR record is satisfactory for the procedure"
Else
MsgBox reply & "'s INR record is not satisfactory for the procedure"
End If
在连接中使用&
使用单词And
:
If Avg < 1.5 And SD < 0.5 Then
函数在if中调用,不需要Call INR
,只需将其用作任何其他函数。
同样优良的做法是命名运行它的工作表。我们可以使用With
块来执行此操作:
With Worksheets("Sheet1") 'Change to your sheet
'Do your code
End With
使用Range变量:
,而不是创建命名范围Set rng = .Range("B:B")
让我们加快速度并取消循环。我们可以使用Match来找到行:
i = Application.WorksheetFunction.Match(reply, rng, 0)
如果找到该名称,它将返回找到它的行。如果不是,它将返回错误。如果出错,我选择跳过,因此i
将保持为0,我们可以在继续之前对其进行测试。
INR的默认设置为False,因此我们无需设置它并保存一些输入:
INR = (Avg < 1.5 And SD < 0.5)
应该足够了
所以:
Public Function INR(Avg As Double, SD As Double) As Boolean
INR = (Avg < 1.5 And SD < 0.5)
End Function
Public Sub PatientINR()
Dim cell As Range, reply As String, i As Long
Dim Avg As Double, SD As Double
Dim rng As Range
reply = InputBox("Enter patient's name", "INR", "Madelyn Carberry")
i = 0
With Worksheets("Sheet1") 'Change to your sheet
Set rng = .Range("B:B")
On Error Resume Next
i = Application.WorksheetFunction.Match(reply, rng, 0)
On Error GoTo 0
If i <> 0 Then
Avg = .Cells(i, 17)
SD = .Cells(i, 18)
If INR(Avg, SD) Then
MsgBox reply & "'s INR record is satisfactory for the procedure"
Else
MsgBox reply & "'s INR record is not satisfactory for the procedure"
End If
Else
MsgBox "Name not Found"
End If
End With
End Sub