0

我正在尝试将“选定文件”工作表中的值复制到单元格(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
4

1 回答 1

0

你不应该需要任何activates 和selects。除非我错过了什么,这应该足够了吧?

Sub Get_Data_From_File()

Dim FileToOpen As Variant
Dim mainFile As Workbook, OpenBook As Workbook
Dim countryName As Variant
Dim Lastrow As Long, i As Long

Set mainFile = ThisWorkbook
countryName = Sheets("SelectFile").Range("B2").Value

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)
    Lastrow = ActiveSheet.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
    
    ThisWorkbook.Sheets("Data").Range("I5") = OpenBook.Sheets(1).Cells(i, 3)
    OpenBook.Close savechanges:=False
End If

End Sub
于 2021-03-28T21:36:03.110 回答