将Excel电子表格数据导入另一个Excel电子表格-然后移至下一行

时间:2019-04-04 15:24:07

标签: excel vba import

我正在将单元格从源电子表格导入到目标电子表格。

使用以下代码,从目标浏览源电子表格并导入数据。

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

我的问题是将数据导入到目标电子表格的下一个空白行。

在处理单个电子表格时,我已使用它添加了新行“ ActiveCell.EntireRow.Insert Shift:= xlDown”,但在此处使用时,它在源电子表格中添加了一行(从中导入数据)

我也尝试过这个,但是无法浏览 https://www.excelcampus.com/vba/copy-paste-another-workbook/

我想浏览并导入excel电子表格,然后在对其他电子表格重复该过程时,它将添加到下一行。

Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

Set targetWorkbook = Application.ActiveWorkbook filter = "Text files(.xlsx),.xlsx" 

caption = "Please Select an input file " 

customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)
Dim targetSheet As Worksheet: Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet: Set sourceSheet = customerWorkbook.Worksheets(1) 

targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").ValuecustomerWorkbook.Close

1 个答案:

答案 0 :(得分:0)

尝试以下操作:(您可能需要根据要将数据传递到的位置来调整范围)

Private Sub CommandButton1_Click()
     Dim customerBook As Workbook, targetWorkbook As Workbook
     Dim filter As String, caption As String, customerFilename As String
     Dim lRow as Long

     Set targetWorkbook = Application.ActiveWorkbook filter = "Text files(.xlsx),.xlsx" 

     caption = "Please Select an input file " 

     customerFilename = Application.GetOpenFilename(filter, , caption)

     Set customerWorkbook = Application.Workbooks.Open(customerFilename)

     Dim targetSheet As Worksheet: Set targetSheet = targetWorkbook.Worksheets(1)
     Dim sourceSheet As Worksheet: Set sourceSheet = customerWorkbook.Worksheets(1) 

targetSheet.Range("A" & lRow).Value = sourceSheet.Range("A1", "C10").Value 
customerWorkbook.Close True

End Sub