我有一堆带有这样字符串的单元格: WFM 1601
还有这个: WFM 2231、WFM 2402
还有这个: 事件 1680、2402、2784
我使用下面的代码将单个单元格中的字符串拆分为多个列(最多 3 列)。
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
lRow = Range("U" & Rows.Count).End(xlUp).Row
Set MyRows = Range("U19:U" & lRow)
For Each cell In MyRows
splitVals = Split(cell.Value, ",")
totalVals = UBound(splitVals)
Range(Cells(cell.Row, ActiveCell.Column + 1), Cells(cell.Row, ActiveCell.Column + 1 + totalVals)).Value = splitVals
Next
现在,我正在尝试找出一种方法来删除所有非数字字符并只留下数字。然后,连接这些数字,它们是我使用的 SharePoint 网站中进程的所有 ID,因此我想将每个数字的 URL 放置在静态字符串的末尾,以及刚刚拆分为的数字旁边单独的列。
这是一个屏幕截图。
我有 U 列,我想生成 V 列到 AA 列。
我可以使用下面的函数仅提取数字。
Function GetNums(target As Range)
Dim MyStr As String, i As Integer
MyStr = ""
If Len(target.Value) = 0 Then GoTo GoExit
If target.Value = "None" Then GoTo GoNone
For i = 1 To Len(target.Value)
If IsNumeric(Mid(target, i, 1)) Then MyStr = MyStr & Mid(target, i, 1)
Next i
GoTo GoExit
GoNone:
GetNums = "None"
Exit Function
GoExit:
GetNums = MyStr
End Function
但是,这不会满足要求,因为它会检查单元格中的所有字符,并且只会变成: WFM 2231, WFM 2402 。 。 。 进本:22312402 我真的需要一些方法来区分这两个ID:2231 2402
最佳答案
我会使用正则表达式来提取数字组。如果事实证明有效数字序列的构成还有其他标准,那么通过更改正则表达式会更容易实现。
以下是事件工作表 A 列中原始数据的示例。
Option Explicit
Sub CreateURL()
Dim RE As Object, MC As Object, M As Object
Const sPat As String = "\b\d+\b" 'whole words that are all digits
Const sBaseURL As String = "htpps://collaborate.process...&ID="
Dim I As Long, J As Long
Dim rSrc As Range, C As Range
'This will be on active sheet
'Suggest you specify actual worksheet
Set rSrc = Range(Cells(1, 1), Cells(Rows.Count, "A").End(xlUp))
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = sPat
.Global = True
End With
For Each C In rSrc
If RE.test(C.Text) = True Then
Set MC = RE.Execute(C.Text)
J = -1
For Each M In MC
J = J + 2
C.Offset(0, J) = M
C.Offset(0, J + 1) = sBaseURL & M
Next M
End If
Next C
End Sub
这是针对 A 列中的数据运行此宏的结果:
这是正则表达式的正式解释,其中包含指向更多细节的链接,希望仍然有效:
\b\d+\b
\b\d+\b
选项:不区分大小写; ^$ 匹配换行符
- Assert position at a word boundary (position preceded or followed—but not both—by an ASCII letter, digit, or underscore)
\b
- Match a single character that is a “digit” (ASCII 0–9 only)
\d+
- Assert position at a word boundary (position preceded or followed—but not both—by an ASCII letter, digit, or underscore)
\b
创建于 RegexBuddy
关于vba - 如何删除单元格中的非数字字符并将结果连接到 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43076380/