I am trying to write a macro that opens an import file dialog box, has a user select a file, and copies/pastes the data from a specific sheet from one workbook into a specific sheet in the open workbook.
This is for a summary report that requires additional data from multiple workbooks.
I'm a little new to VBA, so I can't get it quite right. I can get the file to import into a different sheet, but not into a specific sheet. Any help would be appreciated, If there is a way to do this without macros. I'm open to that as well. Thanks!
Here is my current code:
Sub importDataFromAnotherWorkbook()
' 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 = "Text files (*.xlsx),*.xlsx"
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 = "ImportData"
End Sub
The following should work:
Option Explicit
Public Sub ImportDataFromAnotherWorkbook()
' Get workbook...
Dim targetWorkbook As Workbook
Set targetWorkbook = Application.ThisWorkbook
' get the customer workbook
Dim Filter As String
Filter = "Text files (*.xlsx),*.xlsx"
Dim Caption As String
Caption = "Please Select an input file "
Dim Ret As Variant
Ret = Application.GetOpenFilename(Filter, , Caption)
If VarType(Ret) = vbBoolean And Ret = False Then Exit Sub
Dim wb As Workbook
Set wb = Workbooks.Open(Ret)
'copy into a specific worksheet in your target workbook
wb.Worksheets(1).UsedRange.Copy targetWorkbook.Worksheets("whatever").Range("A1")
'close opened workbook without saving
wb.Close SaveChanges:=False
End Sub
Make sure you know the differences between ThisWorkbook
and ActiveWorbook
. In most cases ThisWorkbook
is what you want and ActiveWorkbook
is only very rarely needed (eg for add-ins):
ThisWorkbook
is the workbook this code is written in (it never changes). ActiveWorkbook
is the workbook that has focus (is on top). This can easily change by a single user click and therefore should be avoided. Also you should not mix up Sheets
and Worksheets
:
Sheets
contains all kind of sheets (chart sheets, worksheets, etc) but … Worksheets
only contains worksheets.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.