Excel-将数据从一个工作表提取到另一个电子表格

时间:2019-10-19 09:43:03

标签: excel vba

我正在使用以下脚本将数据从同一工作簿中的一张纸提取到另一张纸。

Sub Test()
Dim SourceSheet As Worksheet
Dim TargetSheet As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim i As Long

With ThisWorkbook
    Worksheets("Sheet1").Activate
    Set SourceSheet = Worksheets(Range("D2").Value2)
    Set TargetSheet = Worksheets("Sheet1")
End With

LastRow = SourceSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
LastCol = SourceSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column

For i = 1 To LastRow
    For j = 1 To LastCol
        SourceSheet.Cells(i, j).Copy Destination:=TargetSheet.Cells(i + 9, j)
    Next j
Next i

End Sub

我需要将数据提取到另一个电子表格(保存源文件的相同目录)中,提取的数据应从 ROW 50 开始显示。

1 个答案:

答案 0 :(得分:0)

您需要像这样将工作簿打开到Workbook对象中

Sub GetDataExample()

Dim wbDest As Excel.Workbook
Dim TargetSheet As Excel.Worksheet
Dim SourceSheet As Excel.Worksheet

Set wbDest = Workbooks.Open("c:\databases\csv\test1.xlsx")
Set SourceSheet = ThisWorkbook.Worksheets("Sheet2")
Set TargetSheet = wbDest.Worksheets("Sheet1")

With SourceSheet.UsedRange

    LastRow = .SpecialCells(xlCellTypeLastCell).Row
    LastCol = .SpecialCells(xlCellTypeLastCell).Column

    TargetSheet.Range("a50").Resize( _
                        .Rows.Count, _
                        .Columns.Count).Value = .Value

End With

wbDest.Close True

End Sub