VBA Examples – Import Data ( copy data from source file to currentworkbook)

Dim filename As String

Dim sourceSheet As Worksheet

Dim sourceWb As Workbook

Dim fileList As Variant

Dim targetSheet As Worksheet

Dim sRow, iRow, sCol As Integer

Set targetSheet = ThisWorkbook.Sheets(“Sheet1”)

filename = Application.GetOpenFilename(“Excelfiles (*.xlsx), *.xlsx”, Title:=”choose file”, MultiSelect:=False)

Dim j As Integer

Set sourceWb = Workbooks.Open(filename)

Set sourceSheet = sourceWb.Sheets(“Sheets1”)

sCol = sourceSheet.Cells(1, Columns.Count).End(xlToLeft).Column

If sCol <> 8 Then

MsgBox “invalid file format”, vbCritical

Exit Sub

End If

sRow = sourceSheet.Cells(Rows.Count, “A”).End(xlUp).Row

For iRow = 1 To sRow

targetSheet.Cells(iRow, “A”).Value = sourceSheet.Cells(iRow, “A”).Value

targetSheet.Cells(iRow, “A”).Offset(, 1).Value = sourceSheet.Cells(iRow, “A”).Offset(, 1).Value

Next iRow

Leave a Reply