簡體   English   中英

在VBA中使用Lookup功能

[英]Using Lookup function in VBA

我目前正在使用VBA自動生成銷售報告,我在使用動態范圍的VBA插入公式時遇到問題。 我的查找公式查找客戶訂購的最后一周。

當前周是最后一周,並且始終是“總計”列之前的列。 我在本周引用最后一欄時遇到問題。

=LOOKUP(2,1/(CL[@[Week 1]:[Week 17]]>0),COLUMN(CL[[#Headers],[Week 1]:[Week 17]]))

我不知道如何引用標題。
所以我的代碼的第一部分找到了列號,並使用列號我得到了字母引用。 不知道如何使用帶有我的LOOKUP公式的字母

Sub LastOrder()
    Dim strSearch As String
    Dim strSearchEnd As String
    Dim aCell As Range
    Dim endCell As Range
    Dim startingCol As Variant
    Dim endingCol As Variant
    Dim colFirstWeek As Variant
    Dim ColLastWeek As Variant
    Dim firstCheck As Variant
    Dim lastCheck As Variant

    'find the column number for week 1 and total 

    strSearch = "Week 1"
    strSearchEnd = "Total"  

    Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        startingCol = aCell.Column
    End If

    Set endCell = Sheet1.Rows(1).Find(What:=strSearchEnd, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not endCell Is Nothing Then
        endingCol = endCell.Column - 1  
        'this is used to get column number of current week 
    End If

    'Use letter reference 

    firstCheck = Split(Cells(, startingCol).Address, "$")(1)
    lastCheck = Split(Cells(,  endingCol).Address, "$")(1)

    Debug.Print (firstCheck)
    Debug.Print (lastCheck)

    Range("CL[Last Week Ordered]").FormulaR1C1 = _
    "LOOKUP(2,1/(firstCheck:lastCheck>0),COLUMN(firstCheck:lastCheck))

你可以嘗試這個公式:

=LOOKUP(2, 1 / ( [@[Week 1]]:INDEX([@], , COLUMNS([@]) - 1) > 0 ), 
         COLUMN( [@[Week 1]]:INDEX([@], , COLUMNS([@]) - 1) ) )

很少Excel函數(如INDEXOFFSET返回Range引用,因此它們可以與范圍運算符:和VBA中的Range("INDEX(A1:B1, 1, 1)")一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM