1

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

我想让它更灵活,我希望它从特定列(例如 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
4

2 回答 2

1

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

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

ActiveCell.Offset(0, FormulaCol - 1).FormulaR1C1 = _
    "=IF(RC[" & CStr(LookupCol - FormulaCol) & "]=R2C1,1,0)"
于 2013-03-13T17:03:14.407 回答
0

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

这应该够了吧...

于 2013-03-13T17:03:45.677 回答