如何才能在同一个单元格中找到字符后的数字值。
例如:查找01
之后的数字J*
。我有几行,每行都有类似J*01
或 的值J*08
。
目前我正在尝试使用 VBAInStr
函数分隔字符和数字:
Sub zz()
Dim ii As Long, z As Integer, xlastrow As Long
Dim yy As String
xlastrow = Worksheets("Sheet1").UsedRange.Rows.Count
For ii = 1 To xlastrow
yy = "J*"
z = 1
If IsNumeric(Worksheets("Sheet1").Range("B" & ii)) Then
'This line is separating numbers after J* character and pasting to sheet2
Seprate.Find.Range("B" & ii, yy).Value = Worksheet("Sheet2").Range("A" & z)
End If
z = z + 1
Next ii
End Sub
答案1
这是另一个用户定义函数,它将返回特定字符串(前缀)后的所有数字。在参数中,您可以指定要处理的字符串和要使用的前缀。您还可以指定前缀是否区分大小写。默认为不区分大小写,但很容易更改。
UDF 使用正则表达式进行文本处理。首先,我们删除前缀之前的所有内容。然后,我们删除余数中的所有非数字。
===================================
Option Explicit
Function DigitsAfter(sInput, sPrefix, Optional MatchCase As Boolean = False) As String
Dim re As Object
Dim S As String
Dim sPatPrefix As String
Const sPat As String = "\D"
'Intialize Regex engine
Set re = CreateObject("vbscript.regexp")
With re
.Global = True
.ignorecase = Not MatchCase
End With
'Generate the digit prefix
re.Pattern = "(.)"
sPatPrefix = ".*" & re.Replace(sPrefix, "\$1")
'Remove characters up to and including the prefix
re.Pattern = sPatPrefix
If re.test(sInput) = False Then
'Exit if prefix not in string
DigitsAfter = "Digit Prefix not in String"
Exit Function
'now remove all the non-digits that are left
Else
S = re.Replace(sInput, "")
re.Pattern = sPat
DigitsAfter = re.Replace(S, "")
End If
End Function
=====================================
这是一个简短的例程,展示了如何在更大的宏中使用它:
======================================
Option Explicit
Sub TestDigitFunction()
Const S As String = "abc12x97J*24AAA123"
MsgBox S & vbLf & DigitsAfter(S, "J*")
End Sub
======================================
答案2
这解决了您的问题而不是您的示例代码。如果您有如下字符串:
q1w2e3r4asJ*66bvft654
想要提取 J* 后面的两位数字,可以试试这个自定义函数
Public Function RetDigits(sIN As String) As String
Dim lookFor As String, v As String
lookFor = "J*"
RetDigits = ""
If InStr(sIN, lookFor) = 0 Then Exit Function
ary = Split(sIN, lookFor)
If Len(ary(1)) < 2 Then Exit Function
RetDigits = Left(ary(1), 2)
End Function
例如:
编辑#1:
这是一个将返回超过2数字:
Public Function RetDigits(sIN As String) As String
Dim lookFor As String, v As String, ary
Dim i As Long, CH As String
lookFor = "J*"
RetDigits = ""
If InStr(sIN, lookFor) = 0 Then Exit Function
ary = Split(sIN, lookFor)
If Len(ary(1)) < 2 Then Exit Function
For i = 1 To Len(ary(1))
CH = Mid(ary(1), i, 1)
If IsNumeric(CH) Then
RetDigits = RetDigits & CH
End If
Next i
End Function
以下是测试程序:
Sub main()
Dim st As String, out As String
st = "hfskfhjsdfshjJ*123456"
out = RetDigits(st)
MsgBox out
End Sub
答案3
要查找“ ”后面恰好两位数字的值J*
,您不需要 VBA。如果字符串在 A1 中,只需使用:=VALUE(MID(A1;SEARCH("J*";A1)+2;2))
。该SEARCH
函数搜索“ J*
”。MID
获取接下来的两个字符并将VALUE
其转换为一个值。