我正在尝试将“选定文件”工作表中的值复制到单元格(I5)中已创建的名为“数据”的工作表中。
我编写了一个代码,用于在名为“SelectFile”的单独工作表中的单元格 (B2) 中搜索先前输入的国家/地区的人口数量。
这个命令有问题OpenBook.Sheets(1).Range(selectedRow, 3).Copy
。VBA 不读取列号。
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