带有if函数的VBA代码(取自单元格的值)
我有VBA代码,它使用countif函数,并检查值“美国”填充在testing列(请参阅下面的代码) 。
我想使这更加灵活,我希望它从特定列(如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)"
我试图使用简单的function代码= IF(B2 = A2,1,0),并把代码中的A2。 我所有的尝试都返回了语法错误。
我的macros
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
尝试在函数中使用R2C1
而不是A2
。 原因是你正在使用Range.FormulaR1C1
,它只接受RC风格的引用。
将公式分配给单元格的VBA行将如下所示:
ActiveCell.Offset(0, FormulaCol - 1).FormulaR1C1 = _ "=IF(RC[" & CStr(LookupCol - FormulaCol) & "]=R2C1,1,0)"
…“replace"]=""United States"",1,0)"
与"]=" & Range("A2").Value & ",1,0)"
这应该够了吧…