【发布时间】: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")