将最后一行从一个excel文件复制到另一个

时间:2014-12-22 14:50:10

标签: vba

我需要将一个excel文件中的最后一行复制到另一个excel文件中。我计算包含数据的最后一行并将其存储在变量iLastRow中。

Dim wsProduct As Worksheet
With wsProduct
    (iLastRow).Copy
End With
Set exportFile = Workbooks.Open("C:\data.xlsx")
With exportFile.Sheets("exportsheet")
'Paste the copied row on the iLastRow here
End With

提前致谢。

2 个答案:

答案 0 :(得分:0)

要查找您目的地文件的最后一行,您可以使用以下代码:

Dim DestLast as Long
DestLast = .Range("A" & Rows.Count).End(xlUp).Row + 1 'must add one to get to the BLANK row

然后:

.Range("A" & DestLast).PasteSpecial xlPasteValues

答案 1 :(得分:0)

试试这个解决方案。在代码之后我需要注意一些事项。这里的主要想法是简单地设置工作表名称。获取每张纸上的最后一行,并将数据从一张纸复制到另一张,直接设置值而不是复制/粘贴。整个副本发生在一个简单的3行循环中。

'---COPY ENTIRE ROW---  Loop through Cells by column
For lCol = 1 To lastCol
    s2Sheet.Cells(nextS2Row, lCol) = s1Sheet.Cells(lastS1Row, lCol)  
Next lCol

<强>试验:

Private Sub LastRowToExport()

Dim lastS1Row As Long       'Last Source Row
Dim nextS2Row As Long       'Next Target Row
Dim lastCol As Long         'Last Column on Source Sheet
Dim s1Sheet As Worksheet, s2Sheet As Worksheet
Dim source As String        'Source worksheet name
Dim target As String        'Target worksheet name
Dim path As String

    '---SET SHEET NAMES HERE---
    source = "Product"     'Source Worksheet Name
    path = "C:\data.xlsx"  'Target File Path including file name and extension
    target = "exportsheet" 'Target Worksheet Name

    'WARNING - THIS LINE WILL DISABLE NORMAL BREAKING - IN CASE OF LOOP
    Application.EnableCancelKey = xlDisabled    'Disables breaking when opening new book    

    'Define worksheets
    Set s1Sheet = ThisWorkbook.Sheets(source)           'Source Sheet
    Set s2Sheet = Workbooks.Open(path).Sheets(target)   'Target Sheet

    'Get the last row on each sheet and set the NEXT Row on the target.  Also total columns.
    lastS1Row = s1Sheet.Range("A" & Rows.count).End(xlUp).row       
    nextS2Row = s2Sheet.Range("A" & Rows.count).End(xlUp).row + 1   
    lastCol = s1Sheet.Cells(1, Columns.count).End(xlToLeft).column  'Headers in Row 1

    '---COPY ENTIRE ROW---  Loop through Cells by column
    For lCol = 1 To lastCol
        s2Sheet.Cells(nextS2Row, lCol) = s1Sheet.Cells(lastS1Row, lCol)  
    Next lCol

    'WRAP UP, SAVE EXPORTED SHEET, REACTIVATE SOURCE SHEET
    s2Sheet.Activate
    ActiveWorkbook.Close SaveChanges:=True
    s1Sheet.Activate

End Sub

<强> BEFORE:

BEFORE

<强> AFTER:

AFTER

重要提示: 运行上面的代码时,打开第二个工作簿时会有一个中断。为了避免这种情况,您可以添加以下行:已在上面的代码中

'WARNING - THIS LINE WILL DISABLE NORMAL BREAKING - IN CASE OF LOOP
Application.EnableCancelKey = xlDisabled    'Disables breaking when opening new book 

这意味着如果你有一个无限循环,你将无法使用常规手段逃脱它。这段代码不会产生无限循环,因为我已对它进行了测试,但您需要了解它,所以如果您或任何人试图在其他环境中使用它,请知道它具有该潜力并谨慎使用它。

如果您不想添加该行,系统会提示您继续,结束,调试&#34;并选择继续将工作正常。

相关问题