【发布时间】:2018-09-03 04:21:24
【问题描述】:
免责声明-我的情况是具体的,在我的情况下,我的代码有效,因为我知道模式。
我到处都在寻找答案,但我尝试的代码并不完全符合我的要求,如果您正在寻找一组数字,这就是我的解决方案。
就我而言,我正在寻找 7 位数字,从数字 1 开始,在一个带有随机字符串的列中,一些字符串具有其他一些没有的数字。
数字会出现在“1XXXXXX”、“PXXXXXXXX”、“PXXXXXXXXX”这三个场景中(因为有斜线,所以数字比较多)。
以下是字符串的示例:
9797 P/O1743061 465347 Hermann Schatte Earl Lowe
9797 Po 1743071 404440 Claude Gaudette Jose Luis Lopez
9817 1822037 463889 Jean Caron Mickelly Blaise
我的代码
Sub getnum()
'i don't use explicit so i didn't declare everything
Dim stlen As String
Dim i As Integer
Dim arra() As String
Dim arran() As String
Orig.AutoFilterMode = False
Call BeginMacro
LastRow = Orig.Cells(Rows.Count, 1).End(xlUp).Row
Orig.Range("J2:J" & LastRow).Clear
'loop though column
For n = 2 To LastRow
celref = Orig.Cells(n, 4).Value
'split string on white spaces
arra() = Split(celref, " ")
'turn string to multiple strings
For counter = LBound(arra) To UBound(arra)
strin = arra(counter)
'remove white spaces from string
storage = Trim(strin)
lenof = Len(storage)
'if string has 9 characthers, check for conditions
If lenof = 9 Then
'position of first and last charachter
somstr = Mid(storage, 1, 1)
somot = Mid(storage, 9, 1)
If somstr = "P" Or somstr = "p" And IsNumeric(somot) = True Then
'removes Po or PO and keeps only 7 digits
storage = Right(storage, 7)
'stores in column J
Orig.Cells(n, 10).Value = storage
End If
ElseIf lenof = 10 Then
somstr = Mid(storage, 1, 1)
somot = Mid(storage, 10, 1)
'other conditions
If somstr = "P" Or somstr = "p" And IsNumeric(somot) = True Then
'removes Po or PO and keeps only 7 digits
storage = Right(storage, 7)
'stores in column J
Orig.Cells(n, 10).Value = storage
End If
End If
'eliminate comma within
arran() = Split(storage, ",")
If Orig.Cells(n, 10).Value <> storage Then
For counter2 = LBound(arran) To UBound(arran)
strin2 = arran(counter2)
storage2 = Trim(strin2)
'final condition if is 7 digits and starts with 1
If IsNumeric(storage2) = True And Len(storage2) = 7 Then
car = Mid(storage2, 1, 1)
If car = 1 Then
'stores in columns J at specific position
Orig.Cells(n, 10).Value = storage2
End If
Else
If isnumeric(orig.cells(n,10).value) =true and _
len(orig.cells(n,10).value = 7 then
orig.cells(n,10).value = orig.cells(n,10).value
else
Orig.Cells(n, 10).Value = "no po# in D"
End If
Next counter2
End If
Next counter
Next n
Call EndMacro
End Sub
【问题讨论】:
-
请看here。
-
您可以使用
RegEx对象,查找7位数字Pattern = "\d{7}" -
正则表达式需要引用外部库,让你心烦意乱,而且非常慢。在真正的数据库中,您将享受数十万条记录:)
-
@MarY 我说得对,所有三种场景模式都有领先空间吗?可能是 Chr(160) 还是不是?
-
@ user6698332 在这种特定情况下,我不需要 PO 或 Po ,通过单独隔离 'p' 或 'P',我得到了所有情况,我不会写一些我不需要的东西......最后,代码有效,我使用了它,并得到了我需要的所有数字。但这是非常具体的。如果你使用它,你需要检查你的字符串中的限制。