所以我正在做一个项目,该项目的输入来自一个相当笨重的数据库,我对它给我的数据类型零控制。它基本上给了我一个字符串,其中包含数字,包括小数。
“每天 2 次,每次0.5 Tab 。”
每当它显示制表符时,我想获取制表符之前的数字并将其转换为双格式。一旦我有了字符串“0.5”,我就知道如何使用 cdbl 来转换它,但是我如何得到这个字符串有点困难,因为 InStr 只从左到右搜索。我的想法是使用 InStr 查找单词“tab”之前的数字之前的空格,但我无法弄清楚如何对其进行编码。有什么建议么?
InStrRev
从右到左搜索。或者,您可以使用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
是相关指标,您可以执行以下操作:
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 传递给函数,而是只传递值并为其添加修剪
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
要从"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