[英]excel vba - add table column with date based on adjacent cell that includes date and time
我有一個Excel表格(“ Table1”),共有4列。 第三和第四列包含格式化為顯示日期和時間的“時鍾輸入”和“時鍾輸出”信息。 例如 :
6/3/2016 10:54:52 AM
我想在這里做兩件事...首先,我想創建一個新的第三列,它僅讀取日期,格式為“ d-mmm”。 這應該與現在在第4列中找到的日期匹配。
我想做的第二件事是將文本的日期部分從現在的第4列和第5列中刪除。因此,最后,示例數據行可能如下所示(列3:5):
C, D, E
7-Jun, 10:54:52 AM, 4:59:44 AM
到目前為止,這是我需要的代碼:
Sub test()
Dim currentSht As Worksheet
Dim lst As ListObject
Set curretnSht = ActiveWorkbook.Sheets(1)
Set lst = currentSht.ListObjects("Table1")
lst.ListColumns.Add Position:=3
'Not really sure how to do the rest
End Sub
那不是Excel的方式。 日期是數字0代表1/1/1900。 將其加1,第二天您將得到一個小時的值是1/24。
您的方法最大的問題是Excel停止編輯單元格Excel會評估單元格的值。 它仍然看起來像7-Jun,但是Excel更改了單元格格式,並將單元格值更改為6/7/216的7-Jun。 最好讓所有單元格都具有相同的日期。 只需更改單元格格式以顯示所需的結果。 如果您需要計算月份,請使用WorkSheet函數。 =月(A1)
嘗試這個:
Sub Demo()
Range("C1").EntireColumn.Insert '-->insert column
Range("D:D").Copy Destination:=Range("C1") '-->copy column 4 to column 3
Range("C:C").NumberFormat = "d-mmm" '-->format column 3
Range("D:E").NumberFormat = "h:mm:ss AM/PM" '-->format column 4 and 5
End Sub
即使這將工作:
Sub Demo()
Dim currentSht As Worksheet
Dim lastRow As Long
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
lastRow = currentSht.Cells(Rows.Count, "C").End(xlUp).Row '-->get last row with data
currentSht.Range("C1").EntireColumn.Insert '-->insert column
currentSht.Range("C1:C" & lastRow) = currentSht.Range("D1:D" & lastRow).Value '-->copy column 4 to column 3
currentSht.Range("C1:C" & lastRow).NumberFormat = "d-mmm" '-->format column 3
currentSht.Range("D1:E" & lastRow).NumberFormat = "h:mm:ss AM/PM" '-->format column 4 and 5
End Sub
這符合您的規格:
Sub InsertColumnAndFormatDates()
Columns("C:C").Copy
Selection.Insert Shift:=xlToRight
Application.CutCopyMode = False
Columns("C").NumberFormat = "d-mmm"
Columns("D:E").NumberFormat = "h:mm:ss AM/PM"
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.