在主子程序中,我必须得到两个用户输入((1)范围地址(例如,A1:C50),(2)Name String(例如,James)),并调用函数子程序(通过传递输入为参数),并通过消息框打印结果,以确定名称是否存在或不存在于范围内。
应从用户输入搜索范围和名称。如何编写Function子例程和调用子?这是我到目前为止所做的。
Function NameExists(name As String, area As Range) As Boolean
If name = area.Value Then
NameExists = True
Else
NameExists = False
End If
End Function
Sub Main()
Dim NameExists As Boolean
Dim name As String
name = InputBox("Enter a Name")
area = InputBox("Enter a Range")
If NameExists = True Then
MsgBox name & " Has Been Found"
Else
MsgBox name & " Has Not Been Found"
End If
End Sub
答案 0 :(得分:0)
您需要实际调用函数来检查它是否存在,并传递您已经输入用户的名称和区域变量。这是一个粗略的例子:
Sub Main()
Dim nm As String
Dim ar As String
nm = InputBox("Enter a Name")
ar = InputBox("Enter a Range")
If NameExists(nm, ar) = True Then
MsgBox nm & " Has Been Found"
Else
MsgBox nm & " Has Not Been Found"
End If
End Sub
Private Function NameExists(name As String, area As String) As Boolean
Dim myRange As Range
Set myRange = Range(area)
For Each myCell In myRange
If myCell.Value = name Then
NameExists = True
Exit For
End If
Next
Set myRange = Nothing
End Function