根据其他单元格重复或更改单元格值

时间:2015-11-10 15:37:47

标签: excel vba excel-vba excel-2010

我有一个宏,它根据用户对起始值的提示填充G列中的值(从单元格G2开始),然后通过每次向该值添加10来重复到列的末尾。

Sub Macro1()

Dim TagName As String
Dim TagNum As Long, k As Long

' Prompts user for tag names/numbers
TagName = InputBox("What is the product tag name? Ex. APPLE")
TagNum = InputBox("What is the starting tag #? Ex. 10")


' Set values in column G, up to last row in column J
k = 0
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
End With

With ActiveSheet.Range("G2")
    For i = 1 To LastRow Step 1
        .Item(i + 0) = TagName & "_" & TagNum2 + k
        k = k + 10
    Next
End With

End Sub

如果C列在每一行中都有唯一值,那么这种方法非常有效,如下所示: Before

但是如果C列中的值重复,我希望G列中的值相同,如下所示: enter image description here

1 个答案:

答案 0 :(得分:1)

我认为有几个错误。这是你在尝试什么?

Sub Sample()
    Dim TagName As String, sTag As String
    Dim TagNum As Long, k As Long

    ' Prompts user for tag names/numbers
    TagName = InputBox("What is the product tag name? Ex. APPLE")
    TagNum = InputBox("What is the starting tag #? Ex. 10")

    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        k = TagNum
        .Range("G2").Value = TagName & "_" & k
        For i = 3 To LastRow
            '~~> Increment k only if the values do not match
            If .Range("C" & i).Value <> .Range("C" & i - 1).Value _
            Then k = k + 10

            .Range("G" & i).Value = TagName & "_" & k
        Next
    End With
End Sub

我在输入框中选择了“Apple”和“10”

enter image description here