问题描述
我使用的功能允许我查看一串文本,并评估它是否由字母组成。它位于一个名为General的模块中。通用模块只存在于公共函数和变量中。函数代码如下所示:
I'm using a function that allows me to review a string of text and evaluate if it is composed of letters. It is housed in a module called "General". The general module only exists to house public functions and variables. Function code is listed below:
Public Function IsAlpha(strValue As String) As Boolean
Dim intPos As Integer
For intPos = 1 To Len(strValue)
Select Case Asc(Mid(strValue, intPos, 1))
Case 65 To 90, 97 To 122
IsLetter = True
Case Else
IsLetter = False
Exit For
End Select
Next
End Function
接下来我有两个if例程来评估用户窗体中的文本框的前2个字符。第一个例程询问第一个字符是否为数字,第二个例程询问第二个字符是否为alpha。目前,当IsAlpha测试为True而不是生成MsgBox时,第二个if例程将我从子例程中弹出。 IsAlpha函数是否被正确调用?
Next I have two "if" routines that evaluate the first 2 characters of a textbox in my userform. The first routine asks if the 1st character is numeric and the second routine asks if the 2nd character is alpha. Currently, the second "if" routine is ejecting me from the sub-routine when IsAlpha tests True, rather than generating the MsgBox. Is the IsAlpha function not being called correctly?
如果程序代码如下:
Private Sub CmdMap_Click()
With TxtDxCode
If IsNumeric(Left(Me.TxtDxCode.Text, 1)) Then
MsgBox "Incorrect DX Code format was entered. ", vbExclamation, "DX Code Entry"
TxtDxCode.Value = ""
TxtDxCode.SetFocus
Exit Sub
End If
If IsAlpha(Left(Me.TxtDxCode.Text, 2)) Then
MsgBox "Incorrect DX Code format was entered. ", vbExclamation, "DX Code Entry"
TxtDxCode.Value = ""
TxtDxCode.SetFocus
Exit Sub
End If
End With
推荐答案
为什么不使用正则表达式?然后没有涉及到循环:
Why don't you use regular expressions instead? Then there's no loops involved:
Public Function IsAlpha(strValue As String) As Boolean
IsAlpha = strValue Like WorksheetFunction.Rept("[a-zA-Z]", Len(strValue))
End Function
此外,当您创建用户定义函数(UDF)时,您需要确保将返回值分配给实际函数的名称,在这种情况下 IsAlpha
- 不是 IsLetter
否则该值永远不会被传回。
Also, when you create a User-Defined Function (UDF) you need to ensure that the return value is assigned to the name of the actual function, in this case IsAlpha
- not IsLetter
otherwise the value will never be passed back.
这篇关于如何检查一个字符串是否只包含字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!