VBA将Dim设置为“= RC [##]”

时间:2015-06-17 15:09:19

标签: excel vba excel-vba

我已经在列T中填充了一个返回double的公式。例如,T8具有公式= S8 / K8(但这不太重要)。

您可以通过查看代码来理解代码,但我的问题来自 years = "=RC[14]" ,它会返回类型不匹配错误。

Dim years As Double

For Each Cell In Range("$F$8:$F$" & lastrow)
    years = "=RC[14]"

    If years = 0 Then
        ActiveCell.FormulaR1C1 = "No inventory"
    End If
    If years < 1 And years <> 0 Then
        ActiveCell.FormulaR1C1 = "Less than a year's worth of inventory"
    End If
    If years > 1 Then
        If Int(years) = 1 Then
            ActiveCell.FormulaR1C1 = "No Activity Required - OH qty exceeds EAU 1 year"
        Else: ActiveCell.FormulaR1C1 = "No Activity Required - OH qty exceeds EAU " & Int(years) & "years"
        End If
    End If
Next

另外,我知道我的If-Else巢可能更干净,但我对VBA不是很有经验,这对我来说是一个非常简单的方法。

感谢您的帮助!

修改

我现在必须选择我想要编辑的单元格范围:

Range("$F$8:$F$" & lastrow).Select
For Each wCell In Range("$F$8:$F$" & lastrow)
    years = wCell.Offset(0, 14).Value                    
    If years = 0 Then
        ActiveCell.FormulaR1C1 = "No inventory"
    End If
    If years < 1 And years <> 0 Then
        ActiveCell.FormulaR1C1 = "Less than a year's worth of inventory"
    End If
    If years > 1 Then
        If Int(years) = 1 Then
            ActiveCell.FormulaR1C1 = "No Activity Required - OH qty exceeds EAU 1 year"
        Else: ActiveCell.FormulaR1C1 = "No Activity Required - OH qty exceeds EAU " & Int(years) & "years"
        End If
    End If
Next

1 个答案:

答案 0 :(得分:2)

您将double设置为字符串值。您需要使用Range对象引用您的范围。要进行相对引用,请使用“偏移”功能。请不要将Cell用作变量名,因为这是Excel中的保留字。

相应地修改:

Dim years As Double
Dim wCell As Range

For Each wCell In Range("$F$8:$F$" & lastrow)
    years = wCell.Offset(0,14).Value