复制并将整个工作表移动到另一个工作簿。 1mil行到65536行

时间:2016-09-01 12:17:53

标签: excel vba excel-vba compatibility

以下是我的代码的一部分,涉及将整个命名工作表从一个主文件复制到正在处理的新未保存文件:

ActiveWorkbook.Sheets("VehicleList").Copy _
   After:=Workbooks(2).Sheets(1)

所以这可以很好地将工作表放入工作簿2但是现在我们正在处理的文件处于旧的excel模式,由于旧的excel具有较少的行而导致以下错误:

  

“Excel无法将工作表插入目标工作簿,因为它包含较少的行和列”

如何在不破坏代码的情况下将副本调整并粘贴到Workbooks(2)?我认为定义一个1000行的范围来复制和移动会起作用,但这也给出了一个错误。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

假设您只想要这些值(即我通过不进行复制粘贴加速它),您可以这样做:

Select Dealer_ID, Max(LastModifiedDate)as MostRecentUpdate
from Inventory 
group by Dealer_ID 
having LastModifiedDate < getdate() - 30
order by MAX(LastModifiedDate)

答案 1 :(得分:1)

我喜欢以下

Option Explicit

Sub main()
    Dim targetWs As Worksheet

    With Workbooks("MyWorkbookname").Sheets("VehicleList") '<--| fully qualify reference wanted worksheet in the wanted workbook
        Set targetWs = SetOrGetSheet(Workbooks(2), .name) '<--| get the (new) target worksheet on the target workbook named after referenced sheet
        Intersect(.Range("A1:F1000"), .UsedRange).Copy targetWs.Cells(1, 1) '<--| copy range to target worksheet on the target workbook
        If targetWs.name <> .name Then MsgBox "a new sheet has been created in " & targetWs.Parent.name & " with name " & targetWs.name
    End With
End Sub

Function SetOrGetSheet(targetWb As Workbook, shtName As String) As Worksheet
    targetWb.Worksheets.Add '<--| add a new sheet in the target workbook

    On Error Resume Next
    Set SetOrGetSheet = targetWb.Worksheets(shtName) '<--| try and get any possible target workbook sheet with the passed name
    If SetOrGetSheet Is Nothing Then targetWb.ActiveSheet.name = shtName '<--| if target workbook has no worksheet with passed name then name the new one after it
    Set SetOrGetSheet = targetWb.ActiveSheet 'return the new worksheet
End Function

你是否应该担心你的复制范围可能超过65行和/或256列而不是你应该添加它的大小检查

修改仅适用于粘贴的值

如果您对粘贴值感兴趣,那么您可以如下所示:

Sub main()
    SetOrGetSheet(Workbooks(2), "VehicleList").Range("A1:F1000").value = ActiveWorkbook.Sheets("VehicleList").Range("A1:F1000").value '<--| copy values form source to target worksheet
End Sub

虽然SetOrGetSheet()功能保持与上述相同

正如您可能已经猜到function是否有更通用的方法,您可能需要(或只是拥有)来处理目标的可能性具有以&#34; VehicleList&#34; 已命名的工作表的工作簿