如果为true,则在单元格值上使用字符串

时间:2015-07-17 14:17:46

标签: excel-vba vba excel

如果ct是新副本,我怎么可能重置ct重新开始?

Dim Last As Long
Dim ct As Long

Last = Range("A" & Rows.Count).End(xlUp).Row
ct = ct + 1

For Each cell In Range("A1:A" & Last)
If cell. DupeUnique = xlDuplicate Then
cell.Offset(0, 1).Value = cell.Value & "-" & ct
End If
Next

代码前的数据示例:

0345867   345867

0345867   345867

0345831   345831

0345831   345831

0345831   345831

数据示例:

0345867   345867-1

0345867   345867-2

0345831   345831-3

0345831   345831-4

0345831   345831-5

我希望它做的数据示例:

0345867   345867-1

0345867   345867-2

0345831   345831-1

0345831   345831-2

0345831   345831-3 

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

Sub AdCounter()
Dim Last As Long
Dim ct As Long

Last = Range("A" & Rows.Count).End(xlUp).Row
ct = 1

For i = 2 To Last 'I start from 2 because I think in the 1th are header
Cells(i, "A").Select
If Cells(i, "A") = Cells(i - 1, "A") Then
    Cells(i, "B") = Cells(i, "A") & "-" & ct
    ct = ct + 1
Else
    ct = 1
    Cells(i, "B") = Cells(i, "A") & "-" & ct
    ct = ct + 1
End If
Next
End Sub

只有您的日期从A列开始

,上述代码才有效

答案 1 :(得分:0)

将你的计数器放入你的循环中。跟踪最后一行并进行比较。如果是重复,请重置您的计数器。

Dim lRow As Long
Dim ct As Long
Dim lDuplicate as Long
Dim ws as excel.worksheet
lRow = 1
Set ws = ActiveWorkbook.Sheets("Sheet1")

Do While lRow <= ws.UsedRange.Rows.count
    'Check if this row is the same as the last
    if ws.range("A" & lrow) = lDuplicate then
        'If it is, reset your counter
        ct = 1
    End If

    'Write your incremented value
    ws.range("B" & lrow).value = ws.range("A" & lrow).value & "-" & ct

    lDuplicate = ws.range("A" & lrow).value
    ct = ct + 1

    lRow = lRow + 1
Loop