使用VBA - 根据特定值插入VLOOKUP

时间:2014-02-09 17:08:00

标签: excel vba excel-vba

我正在尝试使用VLOOKUP函数从另一个文件中检索数据,但这只会发生,具体取决于是否有任何3项数据出现在第8列(H)中

OLY

OLY - QUO

OLY - PRO


我有以下内容并且知道这不正确

Sub BlockAllocationsVlookupAll()

Dim x As Long
For x = 1 To 65536

If InStr(1, Sheet1.Range("$H$" & x), "OLY") > 0 Then
Sheet1.Range("$I$" & x) = Sheet1.Range("$I$" & x) & "sometext"
End If
Next

End Sub

我知道上面的内容并没有完全符合我的需要,任何人都可以帮助完成需要编辑的内容以包含下面的Vlookup

=VLOOKUP(A21,'[001 - Allocations - Blocks.xls]CurrentDayAll'!$1:$65536,9,FALSE)

另一个问题是VLOOKUP指向的单元格也会因报告长度的变化而发生变化

感谢您提供任何帮助

1 个答案:

答案 0 :(得分:0)

<强> UPD:

如评论所示,

  • H位于Allocations.xls工作簿
  • 有一套标准
  • 只有当H列中的相应单元符合任何一个标准时,才应将
  • 公式放在单元格中。

工作代码:

Sub BlockAllocationsVlookupAll()

    Dim x As Long
    Dim lastrow As Long
    Dim searchCriterias As String
    Dim wb As Workbook
    Dim ws As Worksheet

    'specify correct path to your workbook
    Set wb = Workbooks.Open("C:\Allocations.xls")
    'If workbook is already opened use next line
    'Set wb = Workbooks("Allocations.xls")
    Set ws = wb.Worksheets("Current Day")

    searchCriterias = "|OLY|SVC|SVC-PRO|SVC-QUO|EUR|EUR-PRO|EUR-QUO|"

    With ws
        lastrow = .Cells(.Rows.Count, "H").End(xlUp).Row

        For x = 4 To lastrow
            If InStr(1, searchCriterias, "|" & .Range("H" & x) & "|") > 0 Then
                .Range("I" & x).Formula = "=VLOOKUP(A" & x & ",'[001 - Allocations - Blocks.xls]CurrentDayAll'!$A:$I,9,FALSE)"
            End If
        Next
    End With

    'Comment next line if you don't want to close wb
    wb.Close (True)
    Set wb = Nothing
End Sub