简体   繁体   English

Excel VBA-检查数字序列并在必要时替换下一个或最后一个值

[英]Excel VBA - Checking a Sequence of Numbers and Replacing Next or Last Value if Necessary

I am having an extreme difficulty trying to solve this problem. 我很难解决这个问题。 I've tried using case statements and if/else statements with no luck. 我试过使用case语句和if / else语句,但没有运气。 Here is my problem! 这是我的问题! I have a sequence of numbers in one column such as 42,43,49,50 where 42 is always followed with the value 43 and where 49 is always followed with a value of 50. 我在一列中有一个数字序列,例如42,43,49,50,其中42始终跟数值43,而49始终跟数值50。

Sometimes I have a sequence of numbers where they are out of order such as 42,43,49,43. 有时我有一个数字序列,其中的数字顺序不正确,例如42,43,49,43。 In this case I need to change the pattern to 42,43,49,50. 在这种情况下,我需要将模式更改为42,43,49,50。 In another case I have a sequence of numbers such as 42,50,49,50 where I need to change the pattern to 49,50,49,50. 在另一种情况下,我有一个数字序列,例如42,50,49,50,需要将模式更改为49,50,49,50。

Here is my logic: 1st case... If cell = 50 go back to last cell and if that cell = 43 change that cell value to a 49. 2nd case... If cell = 49 go to next available cell and if that cell = 43 change that value to a 50. Keep in mind there are going to be empty cells that have to be dealt with like in the following column. 这是我的逻辑:第一种情况...如果单元格= 50,则返回最后一个单元格,如果该单元格= 43,则将该单元格的值更改为49。第二种情况...如果单元格= 49,则转到下一个可用单元格,如果cell = 43将该值更改为50。请记住,必须处理空白单元格,如下面的列所示。

A 42 "empty" 43 "empty" 49 "empty" "empty" "empty" 43 A 42“空” 43“空” 49“空”“空”“空” 43

Let me know if you all need more clarification and thank you for looking and helping! 让我知道您是否需要更多说明,感谢您的帮助! I hope I followed the question format and sorry if I did not! 我希望我遵循问题​​格式,如果没有,对不起!

Thank you, thank you!!! 谢谢谢谢!!!

Something like this... 像这样

Sub Tester()

Dim c As Range, i As Long, vLast

    Set c = Cells(Rows.Count, 1).End(xlUp)

    Do While c.Row >= 2
        If Len(c.Value) > 0 Then
            If Len(vLast) > 0 Then
                If vLast = 50 Then c.Value = 49
                If vLast = 43 Then c.Value = 42
            End If
            vLast = c.Value
        End If
        Set c = c.Offset(-1, 0)
    Loop

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM