【发布时间】:2023-03-22 02:45:01
【问题描述】:
我有以下代码创建新列“M”并在逗号分隔符之后将列“L”中的日期值粘贴到它。问题不是所有值都粘贴为数字日期,尽管它们显示为数字日期。导致我在创建数据透视表并需要按日期对列标题进行排序的地方进一步出现问题。还有一些日期只有日期为 yy 而不是 yyyy
With Sheets("DataSheet")
newLastRow = pasteRowIndex
If IsArray(v) Then
.Columns(13).Insert Shift:=xlToRight
For i = 1 To newLastRow
If InStr(1, .Cells(i, "L"), ",") Then
.Cells(i, "M").Value = Split(.Cells(i, "L"), ",")(1)
不确定下一行是否正确
Cells(i, "M").NumberFormat = "dd/mm/yyyy"
End If
Next i
End If
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow1 As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
'Switch off error masking
On Error GoTo 0
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("DataSheet")
'With DSheet
'Define Data Range
LastRow1 = DSheet.Cells(Rows.Count, "B").End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, "B").Resize(LastRow, 20)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange)
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="MilestonePivotTable")
'Insert Row Fields
With PTable.PivotFields("Contract Identifier")
.Orientation = xlRowField
.Position = 1
End With
With PTable.PivotFields("SOW ID")
.Orientation = xlRowField
.Position = 2
End With
With PTable.PivotFields("Resource Name")
.Orientation = xlRowField
.Position = 3
End With
With PTable.PivotFields("Deliverable")
.Orientation = xlRowField
.Position = 4
End With
'Insert Column Fields
With PTable.PivotFields("Milestone Date")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Milestone
Date").AutoSort xlAscending, "Milestone Date"
'Insert Data Field
With PTable.PivotFields("Milestone Date")
.Orientation = xlDataField
.NumberFormat = "0"
End With
End Sub
【问题讨论】:
-
我建议改用 Text to Columns。问题是 vba 喜欢
mm/dd/yyyy格式的日期并尝试将其转换为这样。因此,如果您的字符串采用dd/mm/yyyy格式,vba 会将其保留为字符串。 -
或者您可以解析字符串并在 vba 中创建自己的日期,然后分配该值和格式。如果您提供数据示例,但该示例无法正确转换,我们可能会提供更多帮助。
-
.Cells(i, "M").Value2 = Split(.Cells(i, "L"), ",")(1) -
@Scott Craner 我更新了显示excel的截图,你可以看到黄色高亮的两个是不成功的,但夹在它们之间的是一个成功的结果。最好不要将任何不是日期的内容复制到新列中,您可以看到一些 cmets 已被占用。
-
你想如何处理像
31/2/18这样的字符串(在你的第一行),因为它不能被翻译成一个有效的日期?