vba - 如何删除单元格中的非数字字符并将结果连接到 URL?

标签 vba excel

我有一堆带有这样字符串的单元格: 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 放置在静态字符串的末尾,以及刚刚拆分为的数字旁边单独的列。

这是一个屏幕截图。

enter image description here

我有 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 列中的数据运行此宏的结果:

enter image description here

这是正则表达式的正式解释,其中包含指向更多细节的链接,希望仍然有效:

\b\d+\b

\b\d+\b

选项:不区分大小写; ^$ 匹配换行符

创建于 RegexBuddy

关于vba - 如何删除单元格中的非数字字符并将结果连接到 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43076380/

相关文章:

ms-access - Access SQL 中的 CDec 的行为与从 Access VBA 使用时不同

javascript - 使用javascript从html表导出到excel时隐藏列

vba - 打开网站,在 VBA 中查找特定值并将值返回到 Excel

vba - 使用 VBA 从列表中消除重复项并将结果复制到单独的工作表中

Excel 条件格式 - 多个条件

xml - 将 Excel 工作表另存为 xml 在某些行周围添加引号

vba - 将突出显示的绿色复制到另一个工作表

excel - 将单元格与 Excel 形状链接

excel - 解析 Outlook 收件人时选择多个条目中的第一个条目

arrays - VBA 中的子数组 - 我想切掉一个维度