我有一份报告,用于导入与工作计划相关的数据,然后根据数据创建图表和统计数据。计算和图表基于表格,表格由VBA填充 - 用户选择文件,然后VBA检查它是否与预期的文件格式匹配,并将所有内容放在正确的位置。
HOWEVER ,代码的专用部分未正确粘贴所有内容。具体来说,有许多列具有日期值,当粘贴时,其中一些(不是一列或特定行,但看似随机的单元格)在粘贴时未被格式化为日期,因此当我在特定时间范围内查找作业时,不会在公式中捕获。
在源文件中,所有数据都100%保存为日期值(如果我对数据进行过滤,则按年份分组,如果我使用测试单元,则可以扩展到月/日/时间+要向显示下一个日期的单元格添加1)。一旦粘贴到目标表单中,则一些仍然是日期值,但有些似乎是文本并显示为dd / mm / yyyy hh:mm但是从计算中错过了。如果我进入这些单元格,请按F2然后按Enter键,然后单元格将更改为日期值(右对齐,然后包含在日期范围公式中)。
以下是代码:
Public Sub importdata()
Dim wb1, wb3 As Workbook
Dim ws1, ws3 As Worksheet
Dim lrow As Long
Dim WOtable As ListObject
Dim searchcell As Range
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("Dashboard")
Set WOtable = ws1.ListObjects("workorder")
WOfile = Application.GetOpenFilename(FileFilter:="Excel Files (*.CSV),*.CSV", Title:="Select Workorder Extract To Be Opened",MultiSelect:=False)
If WOfile = False Then Exit Sub
Set wb3 = Workbooks.Open(WOfile)
Set ws3 = wb3.Sheets(1)
ws3.Range("M:M, O:O, Q:Q").EntireColumn.Delete
If ws3.Range("A1").Value = "jobnumber" And ws3.Range("B1").Value ="jobdesc" And etc etc Then
lrow = ws3.Range("A1").End(xlDown).Row
ws3.Range("A2:O" & lrow).Copy
WOtable.DataBodyRange(1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Else: MsgBox ("File selected to import workorder information was not in expected format, please check the file and retry.")
End If
wb3.Close False
End Sub
我试图在复制之前添加以下行,以基于我在谷歌上看到的内容强制它,但无济于事:
ws3.Columns("E:K").NumberFormat = "DD/MM/YYYY HH:MM:SS"
感谢您的帮助
答案 0 :(得分:2)
正如评论中所讨论的,将数据推送到变量数组然后将其粘贴到目标的示例用法。一些评论:
编辑子:
Public Sub importdata()
Dim wb1 As Workbook, wb3 As Workbook
Dim ws1 As Worksheet, ws3 As Worksheet
Dim WOtable As ListObject
Dim varTMP As Variant
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("Dashboard")
Set WOtable = ws1.ListObjects("workorder")
WOfile = Application.GetOpenFilename(FileFilter:="Excel Files (*.CSV),*.CSV", Title:="Select Workorder Extract To Be Opened", MultiSelect:=False)
If WOfile = False Then Exit Sub
Set wb3 = Workbooks.Open(WOfile)
Set ws3 = wb3.Sheets(1)
With ws3
.Range("M:M, O:O, Q:Q").EntireColumn.Delete
If .Range("A1").Value = "jobnumber" And .Range("B1").Value ="jobdesc" And etc etc Then
'load data into variant array
varTMP = .Cells(1, 1).CurrentRegion
'If you want to do any data manipulation on the array, do it here
'Paste array
End With
With WOtable.DataBodyRange
Range(.Cells(1, 1), .Cells(0 + UBound(varTMP, 1), 0 + UBound(varTMP, 2))) = varTMP
End With
Else
MsgBox ("File selected to import workorder information was not in expected format, please check the file and retry.")
End If
wb3.Close False
End Sub