所以我正在开发一个项目,该项目来自一个相当笨重的数据库,我无法控制它给我的数据类型。它基本上给了我一个包含数字的字符串,包括小数。
每天2次“ 按0.5标签 。”
每当它显示标签我想在标签前抓取数字并将其转换为双重格式。我知道如何使用cdbl转换它一旦我有字符串“0.5”但我如何得到那个字符串是有点困难,因为InStr只从左到右搜索。我的想法是使用InStr在“tab”之前的数字之前找到空格,但是我无法弄清楚如何编码它。有什么建议吗?
答案 0 :(得分:6)
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)
答案 1 :(得分:1)
假设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传递到函数中,而是只传递Value并为其添加修剪
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
答案 2 :(得分:1)
从"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