在VBA中search包含小数的数字的string

所以我正在从一个相当笨重的数据库input一个项目,我可以控制它给我的数据types。 它基本上给我一个string,其中包含小数的数字。

“每天口服0.5片 ”。

每当它说选项卡,我想抓住之前的数字选项卡,并将其转换为双格式。 我知道如何使用cdbl来转换它,一旦我有string“0.5”,但我怎么得到这个string是有点困难,因为InStr只从左到右search。 我的想法是使用InStr来find前面的单词“标签”之前的数字空间,但我无法弄清楚如何编码。 有什么build议么?

InStrRev从右向左search。 或者,您可以使用StrReverse并使用输出,但我会使用VBScript.Regexp

 Dim text As String text = "take 0.5 Tab by mouth 2 times daily" Dim regex As Object Set regex = CreateObject("VBScript.Regexp") regex.Global = True regex.Pattern = "[\d\.]+(?=\sTab)" Dim test As Object Set test = regex.Execute(text) MsgBox (test(0).Value) 

使用Tab作为相关指标进行更新

假设Tab是相关的指标,你可以这样做:

 Sub ExtractElement() ' column 4 and row 6 contains the text "take 0.5 Tab by mouth 2 times daily" s = Cells(6, 4).Value ' split text into array for each space sAr = Split(s, " ") ' iterate over each element of array For i = 0 To UBound(sAr) - 1 ' if the array element "Tab" is reached If sAr(i) = "Tab" Then ' write the previous array element into the next column Cells(6, 5).Value = sAr(i-1) End If Next End Sub 

请注意,每个单词都被一个“”分隔开来。 我复制了您的文本,并注意到“Tab by”没有分开。

 Sub ExtractCharCode() s = Cells(7, 4).Value For i = 1 To Len(s) Cells(i, 8).Value = Mid(s, i, 1) Cells(i, 9).Value = Asc(Mid(s, i, 1)) Next End Sub 

使用来自用户matzone的答案的变体更新

而不是从matzone传递一个范围到function,我只会通过价值,并添加一个修剪

 Public Function TakeBeforeTab2(s As String) As String s = Mid(s, 1, InStr(UCase(s), "TAB") - 1) TakeBeforeTab2 = Trim(Mid(s, InStr(s, " ") + 1)) End Function 

"take 0.5 Tab by mouth 2 times daily." "0.5"得到"0.5" "take 0.5 Tab by mouth 2 times daily."

 Public Function TakeBeforeTab(r As Range) As String Dim s As String s = r.Value s = Mid(s, 1, InStr(UCase(s), "TAB") - 2) TakeBeforeTab = Mid(s, InStr(s, " ") + 1) End Function