2013-03-08 56 views
1

我有一个使用if函数的宏。它将结果(1或0)放到指定的列中。但是,我想指定列名称的名称。比方说说做if函数,并将这些值赋给名为“Values”的列。下面你可以找到原代码:if function macro - results in a specific column

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

现在如果值列是正确的TEST列这个宏的作品确定什么形象。如果VALUE列的位置远离测试列,那么它不会带来正确的值。我想使宏查找标题“值”以确定列的确切位置值(对于某些文件,它不会是同一列)

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

enter image description here

回答

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 
+0

请看看我的帖子上面我添加了图片和其他信息,我相信可以澄清我试图达到什么。 – mgunia 2013-03-08 14:58:53

+0

请现在就试试。 – www 2013-03-08 15:48:15

+0

它带给我0 G1列这个功能:= IF(K1 =“美国”,1,0)。它看起来像这个函数并没有落在数值上,但是对吗? – mgunia 2013-03-08 16:02:10

相关问题