首页 > 解决方案 > 使用 VBA 将数据从关闭的工作簿导入现有工作表?

问题描述

我有一段 VBA 代码可以将另一个工作簿中的一段数据导入到我打开的 excel 电子表格中,但是,如果导入到我已经创建的工作表中,它不会导入。它每次都想打开一个新工作表。

这是代码:

Sub ImportCurrentMonthData()
' Get workbook...
Dim ws As Worksheet
Dim filter As String
Dim targetWorkbook As Workbook, wb As Workbook
Dim Ret As Variant

Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Excel files (*.xlsb),*.xlsb"
Caption = "Please Select an input file "
Ret = Application.GetOpenFilename(filter, , Caption)

If Ret = False Then Exit Sub

Set wb = Workbooks.Open(Ret)

wb.Sheets(1).Move After:=targetWorkbook.Sheets(targetWorkbook.Sheets.Count)

ActiveSheet.Name = "CurrentMonth"

我已经有一张名为“CurrentMonth”的工作表,我想将数据放入该电子表格。为了发生这种情况,我需要在 VBA 代码中进行哪些更改?

提前致谢。

标签: excelvbaimport

解决方案


如果您只想将数据复制到现有工作表中......

Sub ImportCurrentMonthData()

    ' Get workbook...
    Dim ws As Worksheet
    Dim filter As String
    Dim targetWorkbook As Workbook, wb As Workbook
    Dim Ret As Variant

    Set targetWorkbook = Application.ActiveWorkbook 'ThisWorkbook?

    ' get the customer workbook
    filter = "Excel files (*.xlsb),*.xlsb"
    Caption = "Please Select an input file "
    Ret = Application.GetOpenFilename(filter, , Caption)

    If Ret = False Then Exit Sub

    Set wb = Workbooks.Open(Ret)

    wb.Sheets(1).Usedrange.Copy targetWorkbook.Sheets("CurrentMonth").Range("A1")

推荐阅读