繁体   English   中英

如果函数宏 - 导致特定列

[英]if function macro - results in a specific column

我有一个使用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)"

但我不知道如何更改它以使其如上所述工作。 有人可以帮我吗?

编辑

这是显示我想要实现的图像 在此输入图像描述

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

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

在此输入图像描述

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM