我有 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