Excel VBA: 提取最后一连串数字

提取最后一连串数字,采用从后往前查找的方式,程序中限定了返回结果字符串的长度必须为 15 或 16 或者 17 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Sub ExtractTheLastSuccessiveNumbers()
'Update by 20150702
Dim Rng As Range
Dim WorkRng As Range
Dim xValue As String
Dim OutValue As String
Dim PreviousIsNumber As Boolean
Dim Find As Boolean
Dim index As Integer

On Error Resume Next
xTitleId = "QQ的小工具箱[逆序读取]"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("选择数据范围", xTitleId, WorkRng.Address, Type:=8)

For Each Rng In WorkRng
OutValue = ""
PreviousIsNumber = False
Find = False
xValue = Rng.Value
index = VBA.Len(xValue) + 1

For i = 1 To VBA.Len(xValue)

If VBA.IsNumeric(VBA.Mid(xValue, index - i, 1)) Then

Find = True

If PreviousIsNumber Then
OutValue = VBA.Mid(xValue, index - i, 1) & OutValue
Else
OutValue = VBA.Mid(xValue, index - i, 1)
End If
PreviousIsNumber = True

Else
PreviousIsNumber = False

If Find Then
Exit For
End If

End If
Next

Rng.NumberFormat = "@"
'Rng.NumberFormat = "0"
If VBA.Len(OutValue) = 15 Or VBA.Len(OutValue) = 16 Or VBA.Len(OutValue) = 17 Then
Rng.Value = OutValue
Else
Rng.Value = ""
End If
Next

End Sub

将 xxx.bas 文件导入到 Excel

在 Excel 中按住 Alt + F11 打开 Microsoft Visual Basic Applications 程序,然后将 xxx.bas 文件导入。
Import file.bas

设置【宏】的快捷键

打开【Excel选项】页面,勾选【开发工具】:
Excel选项

设置快捷建
设置快捷建

自定义 Excel 菜单

可以在 Excel 的【选项 > 自定义功能区】中设置自己的菜单,并绑定自己的 Excel VBA 函数。
自定义功能区

参考文献