带有if函数的VBA代码(取自单元格的值)

时间:2013-03-13 16:43:08

标签: excel vba

我有VBA代码,它使用countif函数并检查测试列中是否填充了“美国”值(参见下面的代码)

我想让它更灵活,我希望它从特定列(例如A2)获取数据而不是静态值“美国”。

我知道这段代码应该修改

Debug.Print "=IF(RC[" & CStr(FormulaCol - LookupCol - 1) & "]=""United States"",1,0)"
ActiveCell.Offset(0, FormulaCol - 1).FormulaR1C1 = "=IF(RC[" & CStr(LookupCol -     FormulaCol) & "]=""United States"",1,0)"

我尝试使用简单的函数代码= IF(B2 = A2,1,0)并将A2放入代码中。我的所有尝试都返回了语法错误。

我的宏

Sub bbb()
Dim FormulaCol As Long
Dim LookupCol As Long
Dim TotalRows As Long
Dim TotalCols As Long
Dim i As Long

Sheets("Sheet1").Select
TotalRows = ActiveSheet.UsedRange.Rows.Count
TotalCols = ActiveSheet.UsedRange.Columns.Count

For i = 1 To TotalCols
If Cells(1, i).Value = "Test" Then
    LookupCol = i
    Exit For
End If
Next

For i = 1 To TotalCols
If Cells(1, i).Value = "Values" Then
    FormulaCol = i
    Range("A2").Activate
    Debug.Print "=IF(RC[" & CStr(FormulaCol - LookupCol - 1) & "]=""United States"",1,0)"
    ActiveCell.Offset(0, FormulaCol - 1).FormulaR1C1 = "=IF(RC[" & CStr(LookupCol - FormulaCol) & "]=""United States"",1,0)"
    Cells(2, FormulaCol).AutoFill Destination:=Range(Cells(2, FormulaCol), Cells(TotalRows, FormulaCol))
    With Range(Cells(2, FormulaCol), Cells(TotalRows, FormulaCol))
    .Value = .Value
    End With
End If
Next
End Sub

2 个答案:

答案 0 :(得分:1)

尝试在函数中使用R2C1代替A2。原因是您使用Range.FormulaR1C1,它只接受RC样式的引用。

将公式分配给单元格的VBA行将如下所示:

ActiveCell.Offset(0, FormulaCol - 1).FormulaR1C1 = _
    "=IF(RC[" & CStr(LookupCol - FormulaCol) & "]=R2C1,1,0)"

答案 1 :(得分:0)

...将"]=""United States"",1,0)"替换为"]=" & Range("A2").Value & ",1,0)"

应该这样做......