在操纵日期或时间时格式会发生变化

时间:2014-04-09 16:43:04

标签: excel vba date excel-vba

对于编写Excel宏的常规VB程序员来说,这必须是一个小小的步骤。

我正在尝试将 -HH:-MM:-SS 格式的负时间转换为 HH:MM:SS 并交换前两列的值(它们是同一行中的时间戳)(仅在找到负数日期时)。

日期从负转换为正,但是例如。来自" -01:-05:-14 "它变为" 1:05:14 AM " (首先' 0'缺少和' AM'在最后添加)而不是" 01:05:14 "。

获取交换时间戳的格式也是从" 04/01/2014 04:31:31 AM "到" 2014年4月1日上午4:31:31 " (初始' 0'缺失)。 请帮我解决这个问题?任何新的方法也是受欢迎的。

我使用以下代码:

Dim row As Integer, col As Integer
Dim temp As Integer
Dim TimeText As String
Dim TestArray() As String 'Array to get the negative time, if any
temp = 0
Dim actualRow As Integer
Dim totalRows As Integer
Dim totalCols As Integer

Dim i As Integer
Dim tempSwap As String

totalRows = Application.CountA(Range("A:A"))
totalCols = Application.CountA(Range("1:1"))

For row = 2 To totalRows
actualRow = row - temp
For col = 2 To totalCols
TimeText = ActiveSheet.Cells(actualRow, col).Value

If Left(TimeText, 1) = "-" Then 'initial space and "-" sign

        TestArray() = Split(TimeText, "-")



        For i = 1 To UBound(TestArray)

          MsgBox (TestArray(i))

        Next

        ActiveSheet.Cells(actualRow, col).Value = TestArray(1) + TestArray(2) + TestArray(3) ' We know that there will be 3 array elements and TestArray(0)=""
    'SWAPPING THE COLUMN VALUES
    tempSwap = ActiveSheet.Cells(actualRow, col - 1).Value
    ActiveSheet.Cells(actualRow, col - 1).Value = ActiveSheet.Cells(actualRow, col - 2).Value
    ActiveSheet.Cells(actualRow, col - 2).Value = tempSwap

    temp = temp + 1

End If
Next col
Next row

1 个答案:

答案 0 :(得分:0)

如果您有以下单元格:

<强> -01:-05:-14

选择它们并运行:

Sub FixTime()
    Dim r As Range
    For Each r In Selection
        With r
            v = Replace(Trim(.Text), "-", "")
            .Clear
            .NumberFormat = "hh:mm:ss"
            .Value = v
        End With
    Next r
End Sub