外部工作簿VBA上的Vlookup

时间:2017-10-03 10:11:19

标签: excel vba excel-vba

我不知道它是如何工作的 我有我的活动工作簿。我想从活动表运行宏 1.我想添加2个带标题的columnes。 - 工作
2.我想打开外部文件,它位于我的vloop中。 - 工作
3.我想使用vloop从外部工作簿中的活动工作表中查找我的变量,并将结果保存在我的活动工作表中

Sub ImpFPQ()

    Application.ScreenUpdating = False

    On Error Resume Next

    Dim Imp_Row As Integer
    Dim Imp_Col As Integer
    Dim Baza1 As Workbook
    Dim Baza2 As Workbook
    Dim wksheet As Worksheet
    Dim plik As Variant

    Set wksheet = ActiveWorkbook.ActiveSheet

    'add columns with names

    wksheet.Columns("A:B").Insert Shift:=xlToRight
    wksheet.Columns("A").Cells(1, 1) = "KOD"
    wksheet.Columns("B").Cells(1, 1) = "LICZNIK"

    'open file

    plik = Application.GetOpenFilename(Title:="Wybierz raport")
    If plik = False Then Exit Sub
    Workbooks.Open Filename:=plik

    Set Baza1 = ThisWorkbook 'activesheet
    Set Baza2 = Workbooks(plik) 'external workbook

    Set lastel = Baza2.Range("F3", Range("F3").End(xlDown)).Select

    Set lookFor = Baza1.Cells(2, 4)  'aktualny subsyst do znalezienia
    Set srchRange = Baza2.Sheets(1).Range("A3:lastel")

    Range("A2").Value = Application.VLookup(lookFor, srchRange, 6, False)

    Application.ScreenUpdating = True
    MsgBox "Done!"

End Sub

我有这些列,但行没有结果。有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

改变这个:

If plik = False Then Exit Sub
Workbooks.Open Filename:=plik

Set Baza1 = ThisWorkbook 'activesheet
Set Baza2 = Workbooks(plik) 'external workbook

对此:

If plik = False Then Exit Sub
Set Baza2 = Workbooks.Open(Filename:=plik)

Set Baza1 = ThisWorkbook 'activesheet

因为plik给你一个完整的文件名(包括路径)我不认为它可以用作Workbooks集合的索引

见这里:https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-object-excel

答案 1 :(得分:0)

这应该可以解决问题。

Sub ImpFPQ()

    Application.ScreenUpdating = False

    On Error Resume Next

    Dim Imp_Row As Integer
    Dim Imp_Col As Integer
    Dim Baza1 As Workbook
    Dim Baza2 As Workbook
    Dim wksheet As Worksheet
    Dim plik As Variant
    Dim lastRow As Long
    Dim lookfor As Variant
    Dim srchRange As Range

    Set wksheet = ActiveWorkbook.ActiveSheet

    'add columns with names

    wksheet.Columns("A:B").Insert Shift:=xlToRight
    wksheet.Columns("A").Cells(1, 1) = "KOD"
    wksheet.Columns("B").Cells(1, 1) = "LICZNIK"

    'open file

    plik = Application.GetOpenFilename(Title:="Wybierz raport")
    If plik = False Then Exit Sub
    Workbooks.Open Filename:=plik

    Set Baza1 = ThisWorkbook 'activesheet
    Set Baza2 = Workbooks.Open(plik) 'external workbook

    With Baza2.Sheets(1)
        lastRow = .Cells(.Rows.Count, 6).End(xlUp).Row
    End With

    lookfor = Baza1.Cells(2, 4)  'aktualny subsyst do znalezienia
    Set srchRange = Baza2.Sheets(1).Range("A3:F" & lastRow)

    Range("A2").Value = Application.VLookup(lookfor, srchRange, 6, False)

    Application.ScreenUpdating = True
    MsgBox "Done!"

End Sub