Regex 如何在VBA中使用时间分割
我对VBA非常陌生,对于我正在处理的宏,我尝试拆分以下形式的字符串: “持续时间:\分钟\秒” 我正在尝试从中获取总时间(以分钟为单位)。然而,如果时间少于一分钟,那么看起来 “持续时间:\秒” 我的问题是,如何使用拆分函数来涵盖这两种情况?如果方便的话,甚至不需要使用split,谢谢Regex 如何在VBA中使用时间分割,regex,vba,string,split,Regex,Vba,String,Split,我对VBA非常陌生,对于我正在处理的宏,我尝试拆分以下形式的字符串: “持续时间:\分钟\秒” 我正在尝试从中获取总时间(以分钟为单位)。然而,如果时间少于一分钟,那么看起来 “持续时间:\秒” 我的问题是,如何使用拆分函数来涵盖这两种情况?如果方便的话,甚至不需要使用split,谢谢 例如,如果我有字符串“Duration:6分30秒”,我预期结果为6.5,如果字符串“Duration:45秒”,我预期结果为0.75。定义用户函数: Public Function getMinutes(ByV
例如,如果我有字符串“Duration:6分30秒”,我预期结果为6.5,如果字符串“Duration:45秒”,我预期结果为0.75。定义用户函数:
Public Function getMinutes(ByVal input As String) As Double
Elements = Split(input, " ") 'split the string by space
If InStr(input, "Minutes") > 0 Then 'if the string contains the word minutes
mins = Elements(1) 'the element at index 1 is the minutes
secs = Elements(3) 'the element at index 3 is the seconds
Else 'if not
secs = Elements(1) 'just the element at index 1 is the seconds
End If
getMinutes = mins + secs/60 'return the minutes as they are (they may be zero) and the seconds divided by 60
End Function
像这样使用它:
SampleInput1 = "Duration: 06 Minutes 30 Seconds"
myMinutes = getMinutes(SampleInput1) 'output => 6.5
SampleInput2 = "Duration: 45 Seconds"
myMinutes = getMinutes(SampleInput2) 'output => 0.75
在执行操作之前,您可能需要针对正则表达式进一步测试输入,以确保其具有正确的形式。
.
你的模式是:
持续时间:\d+分钟\d+秒
持续时间:\d+秒
Public Function getMinutes(ByVal input As String) As Double
Elements = Split(input, " ") 'split the string by space
If InStr(input, "Minutes") > 0 Then 'if the string contains the word minutes
mins = Elements(1) 'the element at index 1 is the minutes
secs = Elements(3) 'the element at index 3 is the seconds
Else 'if not
secs = Elements(1) 'just the element at index 1 is the seconds
End If
getMinutes = mins + secs/60 'return the minutes as they are (they may be zero) and the seconds divided by 60
End Function
像这样使用它:
SampleInput1 = "Duration: 06 Minutes 30 Seconds"
myMinutes = getMinutes(SampleInput1) 'output => 6.5
SampleInput2 = "Duration: 45 Seconds"
myMinutes = getMinutes(SampleInput2) 'output => 0.75
在执行操作之前,您可能需要针对正则表达式进一步测试输入,以确保其具有正确的形式。
.
你的模式是:
持续时间:\d+分钟\d+秒
持续时间:\d+秒