改变所需的范围

我是vba的新手,真的很看重这个目前的路障。 我想运行一个select范围的VlookupVlookup将引用每天更新的数据。

  1. 第一天,我想让Vlookup在所选Range ("B2:B4")每个单元格中返回一个值。
  2. 第2天,引用的数据将会改变,我希望所选范围将一列移动到右侧Range("C2:C4")

我想确保每次运行macros时,范围向右移动一列,以比较从一天到下一天的数据变化。

我已经提供了下面的代码,它允许我在Range("B2:B4")运行Vlookup ,但是我还没有弄清楚如何根据下一个空列来改变范围。

这就是说,非常感谢你的帮助,非常感谢。

 Sub FillinBlanks() Dim rng As Range Set rng = Worksheets("Sheet2").Range("b2:b4") For Each cell In rng If IsEmpty(cell) Then cell.FormulaR1C1 = "=vlookup(Sheet2!rc1,Sheet1!r5c6:r1000c8,3,false)" End If Next cell End Sub 

你可以做的是find第2行的最后一列,并简单地加1 。 我假设行1有标题,因此我试图find第2行的最后一列。

看到这个例子。

 Sub FillinBlanks() Dim rng As Range, cell As Range Dim lCol As Long With Worksheets("Sheet2") '~~> Find the last column in row 2 lCol = .Cells(2, .Columns.Count).End(xlToLeft).Column + 1 '~~> Construct your range Set rng = .Range(ReturnName(lCol) & "2:" & ReturnName(lCol) & "4") End With For Each cell In rng If IsEmpty(cell) Then cell.FormulaR1C1 = "=vlookup(Sheet2!rc1,Sheet1!r5c6:r1000c8,3,false)" End If Next cell End Sub '~~> Function to return column name from column number Function ReturnName(ByVal num As Integer) As String ReturnName = Split(Cells(, num).Address, "$")(1) End Function