2013-03-13 43 views
1

我有VBA代碼,它使用countif函數並檢查測試列(請參閱下面的代碼)中是否填充值「United States」。具有if函數的VBA代碼(取自單元格的值)

我想使這更加靈活,我希望它從特定列(例如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 

回答

1

嘗試在函數中使用的R2C1代替A2。原因是你使用的是Range.FormulaR1C1,它只接受RC風格的引用。然後

該公式分配給小區

的VBA線看起來像這樣:

ActiveCell.Offset(0, FormulaCol - 1).FormulaR1C1 = _ 
    "=IF(RC[" & CStr(LookupCol - FormulaCol) & "]=R2C1,1,0)" 
+0

喜大呼拉爾。這樣可行。謝謝。我在想有沒有簡單的方法來指定列標題(我的意思是:找到「地理」列並使用標題下的值)? – mgunia 2013-03-14 09:04:38

+0

@ mmunia你的意思是說你想使用一個任意的列名而不是''Test「'? – ikh 2013-03-14 11:27:19

0

...更換"]=""United States"",1,0)""]=" & Range("A2").Value & ",1,0)"

這應該做的伎倆......

相關問題