Excel VBA PasteSpecial不会一致地粘贴

时间:2017-02-02 14:42:43

标签: excel vba copy-paste

我有一份报告,用于导入与工作计划相关的数据,然后根据数据创建图表和统计数据。计算和图表基于表格,表格由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"

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

正如评论中所讨论的,将数据推送到变量数组然后将其粘贴到目标的示例用法。一些评论:

  • 始终说明每个变量所需的类型,同一行上的逗号分隔变量并非都采用最后一个类型。
  • 与语句一起使用可以使代码更加清晰,并减少excel需要解析的引用量。
  • 由于你没有清除表的内容(只是覆盖它们),我在代码中复制了这种行为,因为我认为它是预期的。

编辑子:

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