使用复制功能VBA

时间:2018-07-23 15:30:53

标签: excel vba excel-vba copy-paste

我正在尝试将所有数据从一个工作表复制并粘贴到完全不同的工作簿中的单独数据中。代码会正常运行,直到实际行尝试复制和粘贴数据为止:运行此行时出现的错误是:

  

“运行时错误'1004':应用程序或用户定义的错误。”

不确定我是否甚至需要With语句...任何帮助将不胜感激! (我也只是出于隐私目的更改了文件名,但它们在我的实际代码中是完整的!)

Option Explicit

Sub btnCopyingData_Click()

' Copying data from one workbook to another
Dim fileDest As String, fileSource As String
Dim wbDest As Workbook, wbSource As Workbook
Dim wsDest As Worksheet, wsSource As Worksheet
Dim lrDest As Long, lrSource As Long

'The FILE that data is being copied TO
fileDest = "C:\Users\rest of path...Tar SAPCL Copy.xlsx"

    'The WORKBOOK that data is being copied TO
    Workbooks.Open Filename:=fileDest
    Set wbDest = Workbooks("Tar SAPCL Copy.xlsx")

        'The WORKSHEET that data is being copied TO
        Set wsDest = wbDest.Worksheets(1)

            'The ROW to which data will be pasted in the destination
            lrDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1
'---------------------------------------------------'
'The FILE that data is being copied FROM
fileSource = "C:\Users\Rest of path...SAPCL_20180720 Part 1.xlsx"

    'The WORKBOOK that data is being copied FROM
    Workbooks.Open Filename:=fileSource
    Set wbSource = Workbooks("SAPCL_20180720 Part 1.xlsx")

        'The WORKSHEET that data is being copied FROM
        Set wsSource = wbSource.Worksheets(1)

            'The LAST ROW of the data being copied
            lrSource = wsSource.Range("A" & wsSource.Rows.Count)


With wsSource
    wsSource.Range("A1:V" & lrSource).Copy Destination:=wsDest.Range("A1" & 
    lrDest)
End With

End Sub

错误在这里:

With wsSource
    wsSource.Range("A1:V" & lrSource).Copy Destination:=wsDest.Range("A1" & lrDest)
End With

2 个答案:

答案 0 :(得分:2)

在您的代码中,您得到的值写在A列的最后一行,该列通常是一个空单元格:

lrSource = wsSource.Range("A" & wsSource.Rows.Count)

将其更改为以下内容:

lrSource = wsSource.Range("A" & Rows.Count).End(xlUp).Row

一些想法如何获得最后一行:


然后更改此:

With wsSource
    wsSource.Range("A1:V" & lrSource).Copy Destination:=wsDest.Range("A1" & 
    lrDest)
End With

对此:

With wsSource
    .Range("A1:V" & lrSource).Copy Destination:=wsDest.Range("A1")
End With

或者根据您的实际需求,也可以这样做:

With wsSource
   .Range("A1:V" & lrSource).Copy Destination:=wsDest.Range("A" & lrDest)
End With

答案 1 :(得分:0)

我的lrSource变量行未完成,因此被记录为0值,而不是实际的行整数值。我修复了这一行,代码现在可以运行。