在宏观的Excel Vlookup与范围

时间:2010-12-23 10:33:01

标签: excel vlookup

我正在尝试将vlookup添加到excel宏中的单元格中,但是我似乎无法获得函数的参数,也不能获取范围函数的参数

请帮助我说明如何编写代码的最后一行:

            RangeStartRow = 2
            RangeStartColumn = 1 + 11 + (3 * (AverageSheetIndex - RowCounter - 1))
            RangeEndRow = LastCol
            RangeEndColumn = 2 + 11 + (3 * (AverageSheetIndex - RowCounter - 1))
            ActiveCell.Formula = WorksheetFunction.VLookup(ActiveWorkSheet.Cells(1, c), ActiveSheet.range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)), 2, False)

我相信代码是直的(更不用说前4行的值),我希望在活动单元格上执行vlookup以查找上面声明的4个值范围内的单元格(1,c)。

请让我知道如何重写我的代码的最后一行。

提前致谢。

1 个答案:

答案 0 :(得分:2)

ActiveCell.Formula需要一个字符串来表示您希望在单元格中拥有的公式。

 ActiveCell.Formula = "=vlookup(" & activecell.offset(0,1).address & ....

我通常首先在工作表中手动创建公式,然后在调试窗口中输入I(对于C3中的公式)

? range("C3").formulaR1C1

然后我根据需要编辑公式,然后将其复制到我的代码中。使用formulaR1C1避免检索字母:对于ActiveCell beeing $ C $ 4,

"=D4" is equivalent to "=RC[1]"
"=$D$4" is equivalent to "=R4C4"

我真的想要检索MyCol的列字母,你可以使用:

split(cells(1,MyCol).address,"$")(1)

为了帮助您重新修改公式,我有时会使用以下子句从调试窗口调用:

Sub RngToVba(src As Range)
'Helps to write VBA code that will reproduce formula from existing sheet.
'writes (to the debug window) the VBA code to re-create the formulae in given range
'by Patrick Honorez - www.idevlop.com
'usage: from debug window, type RngToVba [L14:R14]
'                            or RngToVba range("L14:R14")
'then copy generated code to your module
    Dim c As Range
    For Each c In src
        Debug.Print "range(""" & c.Address & """).formula = """ & _
                    Replace(c.Formula, """", """""") & """"""
    Next c
End Sub
相关问题