如果函数宏 - 导致特定列

时间:2013-03-08 12:23:46

标签: excel vba

我有一个使用if函数的宏。它将结果(1或0)放置到指定的列。但是,我想指定列名的名称。让我们说if do函数并将值带到哪个标题称为“Values”的列中。您可以在下面找到原始代码:

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 = "Values" Then FormulaCol = i
    If Cells(1, i).Value = "Test" Then LookupCol = i
Next

ActiveCell.FormulaR1C1 = "=IF(RC[-1]=""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 Sub

我知道代码的这一部分负责静态指定列:

ActiveCell.FormulaR1C1 = "=IF(RC[-1]=""United States"",1,0)"

但我不知道如何改变它以使其如上所述起作用。有人可以帮我这个吗?

修改

这是显示我想要实现的目标的图像 enter image description here

现在,如果VALUE列适合TEST列,则此宏可以正常工作。如果VALUE列远离测试列,则它不会带来正确的值。我想使宏查找标题“值”以确定值列的确切位置(对于某些文件,它将不是同一列)

编辑2: 这是我使用您当前代码的结果。即使我移动了TEST列旁边的VALUE列,它的行为也是一样的。使用我的代码时,值从C2填充到C9。正如您所看到的,使用您的代码它会带来D1

中的值

enter image description here

1 个答案:

答案 0 :(得分:3)

我不太确定我是否理解了这个问题,但基于测试列更改一列中的值的子例程可能如下所示:

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) & "]=""us"",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