我想将字符串时间列表转换为秒的原始int值。字符串列表如下所示;
2天20小时57分钟57秒4天20小时44分钟59秒0天2小时24分钟35秒
但是我想做的是创建一个函数,该函数将读取一行,然后将几天转换成几秒钟,然后加上剩余的天数。我相信我将通过一个循环来实现这一点,在该循环中,我读取数值,然后在读取字符串“ days”,“ hours”等时停止。但是,我不确定如何在相关时间段内开始计算呢?
这可以使用@Chronocidal提到的Split
方法解决
分割空格将使我们可以跳过对'days''hours'...令牌的解析,然后将其强制转换并乘以正确的因子
Dim dateString As String
dateString = "2 days, 20 hours, 57 minutes, 57 seconds"
Dim valuesArray As Variant
valuesArray = Split(dateString, " ")
'Split into array of strings by splitting on the space character " "
'valuesArray = ["2","days","20","hours","57","minutes","57","seconds"]
'Now we pull out the indexes we are interested in
'And we cast them to Integers from Strings using CInt(String)
Dim days As Integer: days = CInt(valuesArray(0))
Dim hours As Integer: hours = CInt(valuesArray(2))
Dim mins As Integer: mins = CInt(valuesArray(4))
Dim secs As Integer: secs = CInt(valuesArray(6))
'Declare some conversion ratios to clean up and avoid magic numbers
'We have to use Doubles because we could exceed the max Int
Dim day2sec As Double: day2sec = CLng(60) * 60 * 24 'We case the first to Long because VBA evaluates the right side and it would overflow Int
Dim hours2sec As Double: hour2sec = 60 * 60
Dim min2sec As Double: min2sec = 60
Dim totalSeconds As Double
totalSeconds = days * day2sec + hours * hour2sec + mins * min2sec + secs
Debug.Print (totalSeconds)