2014-04-25 108 views
0

我試圖用一個公式來做到這一點,但遺憾的是它依賴於一個循環,該單元格的值dymanically改變動態更改單元格值

我試圖同時學習Excel中快速地做到這一點VB但偏移和小區名稱被擊敗我 - 有人照顧,給我一些代碼:-)

遍歷細胞d到d

if Dn = "999" then 
if C(n-1) = Cn then 
Modify Dn = D(n-1) + 1 else 
Modify Dn = 1 

結束個

例如細胞

C  D 
1852304 4 
1852304 5 
1852319 1 
1852319 999 
1852321 1 
1852326 1 
1852351 1 
1852351 999 
1852351 999 
1852351 999 
1852352 1 
1852353 1 
1852355 1 
1852355 2 
1852355 3 
+1

因爲我們不知道DN,C,Cn是什麼,所以您需要發佈更多的當前代碼。 – Sorceri

回答

1

這是我翻譯上面的邏輯:

Sub sample() 
'~~> Declare Variables recommended 
Dim rng As Range, cel As Range 
'~~> this gets hold of the Range Object you want to work in 
Set rng = Range("D1", Range("D" & _ 
    Rows.Count).End(xlUp).Address) 
'~~> loop through each cell in range 
For Each cel In rng 
    '~~> check the value of current cell in range 
    If cel.Value = 999 Then 
     '~~> use .Offset to check the 
     '~~> adjacent cell in C column and compare 
     If cel.Offset(-1, -1).Value = cel.Offset(0, -1).Value Then 
      '~~> Modify Dn 
      cel.Value = cel.Offset(-1, 0).Value + 1 
     Else 
      cel.Value = 1 
     End If 
    End If 
Next 
End Sub 

結果:假設你有這樣的數據,在你的榜樣。

sample

運行宏將成爲後:

result

這是你想要什麼?

+0

這正是我想要的,謝謝!簡單而強大。 –

相關問題