来自单独的封闭工作簿的VBA vlookup

时间:2019-02-28 21:26:27

标签: excel vba

我正在尝试vlookup并从单独的已关闭工作簿“管道”的A列返回值。 A列中的值是一个公式,我认为这是我的代码未返回关联值的原因(它似乎运行良好,但未返回任何值)。一旦当前工作簿的A列与“管道”工作簿的AN列匹配,“管道”工作簿的A列中的关联值将被粘贴到C列的当前活动工作簿中,因此是情况3。

 Sub Pipeline_Re()
     OptimizeVBA True
     Dim startTime As Single, endTime As Single
     startTime = Timer

     Dim sWb As Workbook
     Dim fWs As Worksheet, sWs As Worksheet
     Dim slRow As Long, flRow As Long
     Dim pSKU As Range, luVal As Range
     Dim lupSKU As Range, outputCol As Range
     Dim vlookupCol As Object
     Dim i As Integer

     Set sWb = Workbooks.Open("B:\pipeline.xlsm")
     Set sWs = sWb.Sheets("Pipeline")
     Set fWs = ThisWorkbook.Sheets("Re")

     slRow = sWs.Cells(Rows.Count, 1).End(xlUp).Row
     flRow = fWs.Cells(Rows.Count, 1).End(xlUp).Row

     Set pSKU = sWs.Range("AN4:AN" & slRow)
     Set lupSKU = fWs.Range("A6:A" & flRow)

     For i = 3 To 3
        ' Put your body here. '
         Set outputCol = fWs.Range(fWs.Cells(6, i), fWs.Cells(flRow, i))
         Select Case i
             Case 3
                 Set luVal = sWs.Range("A4:A" & slRow)
         End Select

         'Build Collection
         Set vlookupCol = BuildLookupCollection(pSKU, luVal)

         'Lookup the values
         VLookupValues lupSKU, outputCol, vlookupCol
     Next i

     endTime = Timer
     Debug.Print (endTime - startTime) & " seconds have passed [VBA]"
     OptimizeVBA False
     sWb.Close False
     Set vlookupCol = Nothing
 End Sub

 Function BuildLookupCollection(categories As Range, values As Range)
     Dim vlookupCol As Object, i As Long
     Set vlookupCol = CreateObject("Scripting.Dictionary")
     For i = 1 To categories.Rows.Count
         vlookupCol.Item(CStr(categories(i))) = values(i)
     Next i

     Set BuildLookupCollection = vlookupCol
 End Function

 Sub VLookupValues(lookupCategory As Range, lookupValues As Range, 
     vlookupCol As Object)
     Dim i As Long, resArr() As Variant
     ReDim resArr(lookupCategory.Rows.Count, 1)
     For i = 1 To lookupCategory.Rows.Count
         resArr(i - 1, 0) = vlookupCol.Item(CStr(lookupCategory(i)))
     Next i
     lookupValues = resArr
 End Sub

 Sub OptimizeVBA(isOn As Boolean)
     Application.Calculation = IIf(isOn, xlCalculationManual, 
     xlCalculationAutomatic)
     Application.EnableEvents = Not (isOn)
     Application.ScreenUpdating = Not (isOn)
     ActiveSheet.DisplayPageBreaks = Not (isOn)
 End Sub

0 个答案:

没有答案