对于Excel VBA中的每个循环,如何在公式中引用单元格地址?

时间:2015-12-14 17:36:11

标签: excel vba excel-vba foreach

我注释掉的代码最初要求用户在将公式附加到单元格后向下拖动公式。我已经修改了下面的程序和switched from a For each cell loop - 这可以用For each循环结构完成吗?利用Cell.address或类似的东西?请假设我的变量都已定义。

Dim client_row As Long
'Dim v As Long
Dim v As Variant
Dim i As Integer
i = 2
client_row = 0

    LASTROW2 = Range("B" & Rows.Count).End(xlUp).Row
    Set rng2 = Range("N2:N" & LASTROW2)
'    For Each cell In rng2
'        If cell.Offset(0, -13) <> "" Then
'        cell.Formula = "=IFERROR(TEXT(IF(F2=""GBP"",($H2-(IF(LEN($C2)=7,BDH($C2&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH($C2&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/$H2/100,IF(E2=""EQ"",($H2-(IF(LEN($C2)=7,BDH($C2&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH($C2&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/$H2,($H2-(IF(LEN($C2)=7,BDH($C2&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH($C2&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/$H2*100)),""0.00""),""PLEASE REVIEW"")"
'        Debug.Print cell
'        End If
'     Next cell

     For Each v In rng2
             If v.Offset(0, -13) <> "" Then
        v.Formula = "=IFERROR(TEXT(IF($F" & i & "=""GBP"",($H2-(IF(LEN($C2)=7,BDH($C2&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH($C2&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/$H2/100,IF(E2=""EQ"",($H2-(IF(LEN($C2)=7,BDH($C2&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH($C2&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/$H2,($H2-(IF(LEN($C2)=7,BDH($C2&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH($C2&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/$H2*100)),""0.00""),""PLEASE REVIEW"")"
        i = i + 1
        Debug.Print i
        End If
     Next v

2 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用rng2.FormulaR1C1属性。它允许您指定relative reference,这意味着您不需要跟踪当前行。

注释掉的部分可以写成如下:

Set rng2 = Range("N2:N" & LASTROW2)
For Each cell In rng2
    If cell.Offset(0, -13) <> "" Then
        cell.FormulaR1C1 = "=IFERROR(TEXT(IF(RC[-8]=""GBP"",(RC[-6]-(IF(LEN(RC[-11])=7,BDH(RC[-11]&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH(RC[-11]&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/RC[-6]/100,IF(RC[-9]=""EQ"",(RC[-6]-(IF(LEN(RC[-11])=7,BDH(RC[-11]&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH(RC[-11]&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/RC[-6],(RC[-6]-(IF(LEN(RC[-11])=7,BDH(RC[-11]&"" ""&""SEDOL"",""PX_LAST"",TODAY()),BDH(RC[-11]&"" ""&""CUSIP"",""PX_LAST"",TODAY()))))/RC[-6]*100)),""0.00""),""PLEASE REVIEW"")"
        Debug.Print cell
    End If
 Next cell

答案 1 :(得分:1)

如您所链接问题中所述here,您还可以使用v.Column获取循环中当前单元格的列。没有像For Each cell In range这样的特殊结构。在这种情况下,单元格只是指向单元格的对象变量,就像示例中的v一样。

为了让您的生活更轻松,只需将v声明为Range,然后IntelliSense就会向您展示v的可能属性和方法。

Luke的答案是设置相对地址的另一种好方法;)