返回列表 上一主題 發帖

[發問] VBA寫Countif的公式進入儲存格

[發問] VBA寫Countif的公式進入儲存格

請教先進:
儲存格內的countif 計算式的原型是 :在A2儲存格內 =countif( C2:C100, ">=" & B2)

如果在VBA的程式碼 型式 應該怎麼寫?:
      range("A2").formula = "=countif(C2:C100, ........... "

其中原型已使用了成對的 ' " ' 及 串接 "&" 的符號, 如果 格位位置(Address)是可變的又怎辦?

謝謝

回復 1# Scott090


    您好:

請試試如下
Range("a2").Formula = Application.WorksheetFunction.CountIf(Range("c2:c100"), ">=" & Range("b2"))

TOP

回復 1# Scott090

使用巨集錄製後已解決:
   Countif 的原型 : =countif(C2:C100, ">=" & B2)

VBA 公式型態:
   RANGE("A2").FORMULA = "=COUNTIF(C2:C100,"">="" & B2)"

   引申加入變數使用;
dim DataPoints%
dim n%

DataPoints = 12345
n = 30
    For i = 1 To n
           Range("AA" & i ).Formula = "=COUNTIF($S$2:$S$" & DataPoints + 1 & ","">="" &  B" & i  & ")"
    Next

TOP

回復 2# dechiuan999


    謝謝熱心協助
你的式子會計算 "值" 到儲存格

原提意是 "寫公式" 到儲存格

TOP

本帖最後由 Scott090 於 2014-8-3 18:59 編輯
回復  Scott090

使用巨集錄製後已解決:
   Countif 的原型 : =countif(C2:C100, ">=" & B2)

VBA  ...
Scott090 發表於 2014-8-3 18:40



Range("AA" & i). 更正:
Range("A" & i).Formula= "=Countif( C2:C" & datapoints +1 & ","">="" & B" & i &  ")"

TOP

回復 3# Scott090

做參考
資料位置及資料長度是變數時的引申使用:
使用 Range.Address

dim DataPoints% , DataCol%
dim n%
dim Rng as Range

DataPoints = 12345
DataCol = 3  '資料欄位 C
n = 30
set Rng  = Range(Cells(2, DataCol), Cells(DataPoints + 1, DataCol))
    For i = 2 To n
           Range("A" & i).Formula= "=Countif(" & Rng.Address & ","">="" & B" & i &  ")"
    Next

TOP

回復 6# Scott090
  1. For i = 2 To n
  2.            Range("A" & i).Formula= "=Countif(" & Rng.Address & ","">="" & B" & i &  ")"
  3.     Next
複製代碼
不用跑迴圈快些
  1. Range("A2:A" & n).Formula = "=Countif(" & Rng.Address(1, 1, xlR1C1) & ","">="" & RC[1])"
複製代碼
感恩的心......(在麻辣家族討論區.用心學習會有進步的)
但資源無限,後援有限,  一天1元的贊助,人人有能力.

TOP

回復 7# GBKEE


    太感恩了
又學了一招

TOP

        靜思自在 : 太陽光大、父母恩大、君子量大,小人氣大。
返回列表 上一主題