根据相邻的单元格动态更改单元格值

时间:2014-04-25 17:15:12

标签: excel vba

我尝试用公式做到这一点,但不幸的是,它依赖于一个循环,其中单元格值被动态地改变

我试图在学习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 个答案:

答案 0 :(得分: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

这是你正在尝试的吗?