gpt4 book ai didi

string - Excel VBA 循环遍历一串数字,直到找到字母

转载 作者:行者123 更新时间:2023-12-02 01:03:52 40 4
gpt4 key购买 nike

我的单元格中有一个字符串,假设它显示“Client Ref:F123456PassPlus”。字符串可能在数字之前没有字母,数字中可能有符号,并且字母和数字之间可能有空格。我只需要提取数字作为变量。我有执行此操作的代码,但它不知道何时停止循环字符串。当出现除数字或符号之外的其他内容时,它应该停止,但它会继续。

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 是包含字符串的单元格。目前,一切正常,它从数字开始,复制它们,并将它们构建成越来越大的字符串,但只有当 intpos 达到 15 时才会停止。

最佳答案

您尝试完成此任务的方式没有任何问题,但我忍不住建议正则表达式:-)

此示例将从位于 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 Regular Expressions 5.5”的引用

有关如何在 Excel 中使用正则表达式的详细信息,包括循环范围的示例 check out this post .

结果:

enter image description here

关于string - Excel VBA 循环遍历一串数字,直到找到字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927728/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com