2011-08-24 30 views
1

考慮:插入COUNTIF公式,當你有變量保存值

Cells(2, "Q").Formula = "=COUNTIF(P$1:P1,P2)=0" 

如何插入這些公式時,我有一個變量持有的價值?

我必須在3550行和4000行somtimes開始公式。這取決於數據。那麼,當我搜索到它時,我什麼也沒找到。他們都使用相同的公式,但我需要在特定的單元格中插入countif函數,可能在300或500 - 它取決於變量值。

Cells(count,"Q").formula = "=COUNTIF(cells($1,"P"):cells(count-1,"P"),cells(count,"P))=0" 

是這樣嗎?好吧,我在某些方面嘗試過,但最終以紅色着重線條。如何將這些公式與變量一起插入?

回答

3

試試這個:

'case 1: if you know the destination range 
Range("Q2").Formula = "=COUNTIF(P$1:P1,P2)=0" 
Range("Q2").Copy Destination:=range("Q3:Q500") 

'case 2: if the destination range is a variable 
'minRow is a Long >= 1 
Range("Q" & minRow + 1).Formula = "=COUNTIF(P$" & minRow & ":P" & minRow & ",P" & minRow + 1 & ")=0" 
Range("Q" & minRow + 1).Copy Destination:=Range("Q" & minRow + 1 & ":Q" & maxRow) 

參考:Issun's answer堆棧溢出 問題How do I insert the formula into the cell when the formula keeps changing with increase in row?

+0

。嗨它不會從Q3開始可能來自Q300我的意思是,U已經給出了結束複製的地方,但不是開始行的結尾,我的意思是從哪裏開始,起始行將不會是總是3可能是300 somtimes。請更新你的答案 – niko

+1

@niko:這是一個例子,你可以自己調整它。無論如何,我編輯了我的回答 – JMax

+0

謝謝你的哥們! – niko