excel - 使用 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 代码中进行哪些更改?
提前致谢。
解决方案
如果您只想将数据复制到现有工作表中......
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")
推荐阅读
- json - 将 JSON 映射到 Apama 事件
- ember.js - Ember:如何通过参数传递多个参数以路由
- javascript - 我可以使用布尔值来解决这个问题吗?
- python - Lambda 事件返回空对象
- mongodb - 使用 min 验证器验证 mongoose 编号字段
- python - python-gdb 错误:Python 异常
类型没有目标 - android - Android杀死小米、华为等后台服务
- angular - ngClass 根据条件仅工作一次,如何使用连续变化的值应用类
- macos - 内存泄漏 Xamarin React 绑定
- selenium - 想要点击 naukri.com 中的第一份工作链接以获取任何关键字,例如通过 selenium 说 java,但它给了我错误