【问题标题】:How to use split in VBA for time如何在 VBA 中使用拆分时间
【发布时间】:2019-07-24 13:36:16
【问题描述】:

我对 VBA 很陌生,对于我正在处理的宏,我正在尝试拆分以下形式的字符串:

“持续时间:__ 分钟 __ 秒”

我正在尝试从中获取总时间(以分钟为单位)。但是,如果时间少于一分钟,那么它看起来像

“持续时间:__ 秒”

我的问题是,我将如何使用拆分功能来涵盖这两种情况?如果这更容易,甚至不需要使用 split,谢谢!

例如,如果我有字符串“持续时间:6 分 30 秒”,我希望结果为 6.5,如果字符串“持续时间:45 秒”,我希望结果为 0.75。

【问题讨论】:

  • 什么形式?你的输入数据是什么样的?你期待什么样的结果?
  • 字符串看起来像“持续时间:06 分 30 秒”或“持续时间:45 秒”,我期望的结果分别是 6.5 和 0.75
  • 您应该编辑您的问题以澄清这一点,因为我根据帖子本身猜测的可能性绝对为零,我相信这适用于遇到此帖子的任何其他人。跨度>

标签: regex vba string split


【解决方案1】:

定义一个用户函数:

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

您可能希望针对正则表达式进一步测试输入,以确保在执行操作之前它具有正确的形式。 Check this brilliant answer to know how to test a string for a pattern using regex in VBA。 你的模式是:

  • Duration: \d+ Minutes \d+ Seconds
  • Duration: \d+ Seconds

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多