将Excel电子表格数据导入包含VBA的另一个Excel电子表格

13

我们需要在Excel电子表格中编写VBA代码,该代码将读取并对第一个工作表中的数据执行操作。

用户将收到包含数据但不包含VBA代码的电子表格。我们需要能够自动将包含数据的电子表格中的数据导入包含VBA代码的电子表格。包含数据的工作表与包含数据的电子表格的工作表具有相同的列格式和数据类型。

理想情况下,您将打开包含VBA代码的电子表格,显示一个用户界面,允许用户浏览到包含数据的电子表格,单击“确定”即可导入数据。

您会如何实现这个过程?必须使用Excel电子表格中的VBA完成此任务。

非常感谢。

2个回答

29

这将帮助您开始:在您自己的Excel工作簿中使用VBA,让它提示用户输入数据文件的文件名, 然后只需将该固定范围复制到目标工作簿中(可以是与您的宏启用的工作簿相同的工作簿,也可以是第三个工作簿)。 以下是演示如何实现这一点的快速VBA示例:

' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
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").Value

' Close customer workbook
customerWorkbook.Close

谢谢 - 这正是我想要的。 - Anthony

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接