循环遍历列,其列由变量指定,其行为i

时间:2014-12-22 19:55:43

标签: excel vba loops vlookup

我正在尝试创建一个宏来使用VLOOKUP自动填充列。宏调用函数FindNectEmpty找到下一个空单元格,并将该单元格设置为变量OpenCellVoucher(这是列标题)。调用相同的函数来查找OpenCellVoucher单元格下面的空单元格(该单元格是可变的FillCellVoucher)。然后,我想要从该单元格开始对该列中的所有单元格执行VLOOKUP。这就是我所拥有的,但我在这一行上遇到错误,需要一个对象。为什么这不是一个对象?有什么想法来解决这个问题吗?

 Range(FillCellVoucher.Column, i).Formula = Application.WorksheetFunction.VLookup(J2,   DollarRanges.Range("$A$2:$B$14"), 2, 1)

Dim OpenCellVoucher As Range
   Dim FillCellVoucher As Range
   Dim lngRow As Long

 Set NextCell = FindNextEmpty(ActiveWorkbook.Sheets("Master").Range("A1"))
   ActiveWorkbook.Sheets("Master").Select
   NextCell.Value = "Dollar Range of Remaining Balance"

   'Find Open Vouchering column
   Set OpenCellVoucher = Worksheets("Master").Range("A1:O1").Find("Open for Vouchering Amt",   =xlPart)   
   'Looks up next empty cell in row
   Set FillCellVoucher = FindNextEmpty(ActiveWorkbook.Sheets("Master").Range("A2"))
   ActiveWorkbook.Sheets("Master").Select
   lngRow = Cells(Rows.Count, OpenCellVoucher.Column).End(xlUp).Row
       For i = 1 To lngRow
   Range(i, FillCellVoucher.Column).Formula = _
   "=VLookup(J" & i + 1 & ", 'DollarRanges'!$A$2:$B$14, 2, 1)"
   Next i

2 个答案:

答案 0 :(得分:1)

在单元格中设置公式时,需要指定astring的公式:

Range(FillCellVoucher.Column, i).Formula = _
    "=VLookup(J2, DollarRanges.Range(" & "$A$2:$B$14" & "), 2, 1)"

我认为“J2”是你希望在细胞衰落时改变的东西。如果这是你的意图那么:

Range(FillCellVoucher.Column, i).Formula = _
    "=VLookup(J" & i + 1 & ", DollarRanges.Range(" & "$A$2:$B$14" & "), 2, 1)"

我不明白“DollarRanges”是什么,但如果这对你有用,那么我不需要知道。

希望这有帮助。

答案 1 :(得分:1)

我明白了!代码肯定可以简化..但这里是:

Dim OpenCellVoucher As Range
   Dim FillCellVoucher As Range
   Dim myAddress As String
   Dim myColumn As String
   Dim myAdd As String
   Dim CellSelect As String

   'Find Open Vouchering column
   Set OpenCellVoucher = Worksheets("Master").Range("A1:O1").Find("Open for Vouchering Amt", lookat:=xlPart)
   'Looks up next empty cell in row
   Set FillCellVoucher = FindNextEmpty(ActiveWorkbook.Sheets("Master").Range("A2"))
   ActiveWorkbook.Sheets("Master").Select
   myAddress = FillCellVoucher.Address
   myAdd = Left(myAddress, 2)
   myColumn = Right(myAdd, 1)
   For i = 1 To RowsUsed
   CellSelect = myColumn & i + 1
   ActiveWorkbook.Sheets("Master").Range(CellSelect).Formula = _
   "=VLookup(J" & i + 1 & ", 'DollarRanges'!$A$2:$B$14, 2, 1)"
   Next i
相关问题