I am trying to copy a value from a "selected file" worksheet into an already created worksheet called "Data" in cell (I5).
I wrote a code to search for number of population from previous entered country in cell (B2) in a separate worksheet called "SelectFile".
There is a problem in this command OpenBook.Sheets(1).Range(selectedRow, 3).Copy
. The VBA does not read the column number.
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim countryName As Variant
Dim Lastrow As Long
Dim mainFile As Workbook
Dim mainsheet As Worksheet
Dim dataSheet As Worksheet
Dim sht As Worksheet
Dim selectedRow As Long
Dim aData() As Variant
Dim i As Long
Set mainFile = ThisWorkbook
Sheets("SelectFile").Activate
Set mainsheet = ActiveSheet
countryName = Range("B2").Value
Sheets("Data").Activate
Set dataSheet = ActiveSheet
Range("I5").Clear
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls,(*.csv*),*csv*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
Set sht = ActiveSheet
Lastrow = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
For i = 1 To Lastrow
If Cells(i, 2) = countryName Then
selectedRow = i
Exit For
End If
Next i
OpenBook.Sheets(1).Range(selectedRow, C).Copy
mainFile.Activate
dataSheet.Activate
Range("I5").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Application.DisplayAlerts = False
OpenBook.Close False
Application.DisplayAlerts = True
End If
Application.ScreenUpdating = True
End Sub