大家好,
我正在使用 Excel VBA。 我希望能够从下面的示例中提取金额和单位。
示例
预期结果
Amt Unit
1 kt
20 kt
300 kb
40 kb
因为数量可能会有所不同,所以我想到使用子字符串方法“Mid”。 我得到“kt”或“kb”的位置,然后通过获取前一个字符来向后移动。 如果是数字,我会一直向后走,直到找到一个空格。
但似乎你不能使用 Mid 向后退,因为我收到错误:
'Get Unit and Amount
id = "kt"
pos1 = InStr(examples, id)
Dim subAmt1 As String
subAmt1 = Mid(examples, pos1, -1)
我也尝试过这个,但我得到一个空字符串而不是数字
subAmt1 = Mid(examples, pos1 - 2, 1)
我读到有一个 StrReverse() 方法,但这是唯一的方法吗? 我很确定 Java Substring 可以使用负索引来向后获取 char,但我不知道 VBA。 有没有人有更好的解决方案?
非常感谢
只有一种方法 - 新年快乐
Option Explicit
Sub DoIt()
Dim s As String
s = "Peter sell 1kt Gold to James"
Debug.Print GetIt(s)
s = "Aplh sell 300kb of Liquid Nitrogen to Liz"
Debug.Print GetIt(s)
End Sub
Private Function GetIt(theLIne As String) As String
Dim v, r
Dim what As String
If InStr(theLIne, "kb") Then
what = "kb"
Else
If InStr(theLIne, "kt") Then
what = "kt"
Else
Exit Function
End If
End If
v = Split(theLIne, what)
r = v(0)
v = Split(r, " ")
r = v(UBound(v))
GetIt = r & " " & what
End Function