【问题标题】:On manipulating date or time the format changes在操纵日期或时间时,格式会发生变化
【发布时间】:2014-04-09 16:43:03
【问题描述】:

这对于普通的 VB 程序员编写 Excel 宏来说一定是小菜一碟。

我正在尝试将 -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”更改为“4/1/2014 4:31:31 AM"(缺少初始的“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

【问题讨论】:

  • 假设最终结果存储在一个名为“ConvertedTime”的变量中,然后使用这个Format(ConvertedTime,"HH:MM:SS")
  • 还要确保excel表格中的列也被格式化为时间("HH:MM:SS")

标签: vba date excel


【解决方案1】:

如果你有这样的单元格:

-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

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    相关资源
    最近更新 更多