Excel VBA通​​过一串数字循环,直到find一个字母

我有一个单元格中的string,可以说它说“客户端参考:F123456PassPlus”。 string在数字之前可能没有字母,可能在数字中有一个符号,字母和数字之间可能有空格。 我只需要提取数字作为一个variables。 我有代码来做到这一点,但它不知道什么时候停止循环的string。 当有数字或符号以外的东西时,它应该停止,而是继续进行。

IsNumber = 1 ref = "" If branch = "" Then e = b Else e = b + 1 End If f = 1 While IsNumber = 1 For intpos = 1 To 15 ref = Mid(x, e, f) f = f + 1 Select Case Asc(ref) Case 45 To 57 IsNumber = 1 Case Else IsNumber = 0 Exit For End Select Next IsNumber = 0 Wend 

那里没有定义的任何可变字母已被定义,e告诉代码在哪里开始复制,x是包含string的单元格。 现在一切正常,从数字开始复制,并把它们build立成一个更大更大的string,但是只有在intpos达到15时才会停止。

我摆脱了Asc检查,并在build立数字“string”之前通过了每个字符添加了一个检查。

 IsNumber = 1 ref = "" If branch = "" Then e = b Else e = b + 1 End If f = 1 While IsNumber = 1 For intpos = 1 To 15 char = Mid(x, e + intpos, 1) f = f + 1 If IsNumeric(char) Then ref = Mid(x, e, f) IsNumber = 1 Else IsNumber = 0 Exit For End If Next IsNumber = 0 Wend 

如何试图完成这个任务没有什么错,但我不能帮助自己推荐正则expression式:-)

这个例子将从A1的string中A1所有非数字,并将结果呈现在消息框中。 使用的模式是[^0-9]

 Sub StripDigits() Dim strPattern As String: strPattern = "[^0-9]" Dim strReplace As String: strReplace = vbnullstring Dim regEx As New RegExp Dim strInput As String Dim Myrange As Range Set Myrange = ActiveSheet.Range("A1") If strPattern <> "" Then strInput = Myrange.Value strReplace = "" With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then MsgBox (regEx.Replace(strInput, strReplace)) Else MsgBox ("Not matched") End If End If End Sub 

确保您添加对“Microsoft VBScript正则expression式5.5”的引用

有关如何在Excel中使用正则expression式的更多信息,包括遍历范围循环的示例, 请查看此文章 。

结果:

在这里输入图像说明

这个代码松散地基于你的工作(产生“12345”)。 对于大string或更复杂的提取需求,我会考虑学习正则expression式COM对象。

 Function ExtractNumber(ByVal text As String) As String ExtractNumber = "" foundnumber = False For e = 1 To Len(text) ref = Mid(text, e, 1) Select Case Asc(ref) Case 45 To 57 'this includes - . and /, if you want only digits, should be 48 to 57 foundnumber = True ExtractNumber = ExtractNumber & ref Case Else If foundnumber = True Then Exit For End Select Next End Function