创建一个将基于文本的时间戳转换为Excel中的YYYY-MM-DD h:ss:mm格式的宏。

huangapple go评论69阅读模式
英文:

Creating a macro that converts a text-based timestamp into YYYY-MM-DD h:ss:mm format in Excel

问题

我得到的数据以 Excel 表格的形式输出,其中有数据收集开始时的时间戳。 时间戳以文本形式存在,格式为 M/DD/YYYY hh:mm:ss.ms,例如 4/21/2023 16:03:41.791。

我想创建一个宏,可以将这个基于文本的时间戳转换为 Excel 可以识别的格式,即 YYYY-MM-DD h:mm:ss。 输出将是 2023-04-21 4:03:41 PM,以前面的示例为例。

这是我目前的代码:

Sub ConvertTimestamp()
    Dim originalTimestamp As String
    Dim convertedTimestamp As String
    
    ' 指定包含原始时间戳的单元格
    originalTimestamp = Range("O2").Value
    
    ' 转换时间戳格式
    convertedTimestamp = Format(CDate(originalTimestamp), "yyyy-mm-dd h:mm")
    
    ' 用转换后的时间戳更新单元格
    Range("O2").Value = convertedTimestamp
End Sub

然而,我遇到了一些错误,即运行时错误 13: 类型不匹配。

我应该如何修改我的脚本以实现我的目标?

英文:

I get data outputted in an excel sheet, where there is a timestamp of the time the data collection started. The timestamp is present in text form, in the form M/DD/YYYY hh:mm:ss.ms, for example 4/21/2023 16:03:41.791.

I would like to create a macro whereby this text-based timestamp is converted into one Excel can recognize, namely YYYY-MM-DD h:mm:ss. Output would be 2023-04-21 4:03:41 PM for the previous example.

Here is what I have so far

Sub ConvertTimestamp()
    Dim originalTimestamp As String
    Dim convertedTimestamp As String
    
    ' Specify the cell containing the original timestamp
    originalTimestamp = Range("O2").Value
    
    ' Convert the timestamp format
    convertedTimestamp = Format(CDate(originalTimestamp), "yyyy-mm-dd h:mm")
    
    ' Update the cell with the converted timestamp
    Range("O2").Value = convertedTimestamp
End Sub

However, I am getting some errors, namely runtime error 13: Type mismatch.

How should I modify my script to acheive my goal?

答案1

得分: 3

这是毫秒引起麻烦。尝试:

' 转换时间戳格式
convertedTimestamp = Format(CDate(Left(originalTimestamp, Len(originalTimestamp) - 4)), "yyyy-mm-dd h:nn")
英文:

It's the milliseconds that cause you trouble. Try:

    ' Convert the timestamp format
    convertedTimestamp = Format(CDate(Left(originalTimestamp, Len(originalTimestamp) - 4)), "yyyy-mm-dd h:nn")

答案2

得分: 2

  • 将日期文本转换为特定格式

函数

' 将4/21/2023 16:03:41.791转换为2023-04-21 16:03:41.791
Function ConvertToMyDate( _
    ByVal DateString As String, _
    Optional ByVal OldDateDelimiter As String = "/", _
    Optional ByVal NewDateDelimiter As String = "-", _
    Optional ByVal DateTimeDelimiter As String = " ", _
    Optional ByVal MiliSecondsDelimiter As String = ".") _
As String
    On Error GoTo ClearError
    
    Dim Result As String

    Dim dPos As Long: dPos = InStr(DateString, DateTimeDelimiter)

    If dPos > 0 Then
        Dim OldDateStr As String: OldDateStr = Left(DateString, dPos - 1)
        Dim OldDate() As String:
        OldDate = Split(OldDateStr, OldDateDelimiter)
        Dim OldTimeStr As String: OldTimeStr = Right(DateString, _
            Len(DateString) - dPos - Len(DateTimeDelimiter) + 1)
        dPos = InStr(OldTimeStr, MiliSecondsDelimiter)
        Dim NewTimeStr As String
        If dPos > 0 Then
            NewTimeStr = Left(OldTimeStr, dPos - 1)
        Else
            NewTimeStr = OldTimeStr
        End If
        Result = OldDate(2) _
            & NewDateDelimiter & Format(CLng(OldDate(0)), "0#") _
            & NewDateDelimiter & OldDate(1) _
            & DateTimeDelimiter _
            & IIf(Len(NewTimeStr) > 0, NewTimeStr, "0:00:00")
    End If

    ConvertToMyDate = Result
    
ProcExit:
    Exit Function
ClearError:
    Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
    Resume ProcExit
End Function

示例

Sub Test()
    Sheet1.Range("B1").Value = ConvertToMyDate(Sheet1.Range("A1").Text)
End Sub

创建一个将基于文本的时间戳转换为Excel中的YYYY-MM-DD h:ss:mm格式的宏。

英文:

Convert Date as Text to Specific Format

创建一个将基于文本的时间戳转换为Excel中的YYYY-MM-DD h:ss:mm格式的宏。

  • Note that the result of the function is a string that will be converted to a date when writing it to a cell but you also have to set the desired formatting of the cell.
  • If you would want to use it as a UDF you would want to modify the function to return a date instead of a string.

The Function

<!-- language: lang-vb -->

&#39; Convert 4/21/2023 16:03:41.791 to 2023-04-21 16:03:41.791
Function ConvertToMyDate( _
    ByVal DateString As String, _
    Optional ByVal OldDateDelimiter As String = &quot;/&quot;, _
    Optional ByVal NewDateDelimiter As String = &quot;-&quot;, _
    Optional ByVal DateTimeDelimiter As String = &quot; &quot;, _
    Optional ByVal MiliSecondsDelimiter As String = &quot;.&quot;) _
As String
    On Error GoTo ClearError
    
    Dim Result As String

    Dim dPos As Long: dPos = InStr(DateString, DateTimeDelimiter)

    If dPos &gt; 0 Then
        Dim OldDateStr As String: OldDateStr = Left(DateString, dPos - 1)
        Dim OldDate() As String:
        OldDate = Split(OldDateStr, OldDateDelimiter)
        Dim OldTimeStr As String: OldTimeStr = Right(DateString, _
            Len(DateString) - dPos - Len(DateTimeDelimiter) + 1)
        dPos = InStr(OldTimeStr, MiliSecondsDelimiter)
        Dim NewTimeStr As String
        If dPos &gt; 0 Then
            NewTimeStr = Left(OldTimeStr, dPos - 1)
        Else
            NewTimeStr = OldTimeStr
        End If
        Result = OldDate(2) _
            &amp; NewDateDelimiter &amp; Format(CLng(OldDate(0)), &quot;0#&quot;) _
            &amp; NewDateDelimiter &amp; OldDate(1) _
            &amp; DateTimeDelimiter _
            &amp; IIf(Len(NewTimeStr) &gt; 0, NewTimeStr, &quot;0:00:00&quot;)
    End If

    ConvertToMyDate = Result
    
ProcExit:
    Exit Function
ClearError:
    Debug.Print &quot;Run-time error &#39;&quot; &amp; Err.Number &amp; &quot;&#39;:&quot; &amp; vbLf &amp; Err.Description
    Resume ProcExit
End Function

An Example

<!-- language: lang-vb -->

Sub Test()
    Sheet1.Range(&quot;B1&quot;).Value = ConvertToMyDate(Sheet1.Range(&quot;A1&quot;).Text)
End Sub

答案3

得分: 0

将以下内容翻译为中文:

"You can do this all in one line (without having to define extra variables):

Range("O2").NumberFormat = "yyyy-mm-dd h:mm"

Give that a try and let me know how it works for you!"

英文:

You can do this all in one line (without having to define extra variables):

Range(&quot;O2&quot;).NumberFormat = &quot;yyyy-mm-dd h:mm&quot;

Give that a try and let me know how it works for you!

huangapple
  • 本文由 发表于 2023年6月12日 11:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定