我有两列数字,它们在一起将是唯一的(复合键)。我想创建一个唯一的 ID 号(第三列),类似于 MS Access 使用主键的方式。我想在 VBA 中执行此操作,但我不知道如何执行此操作。
我的 Excel 中的 VBA 不是很好,所以希望您能看到我已经开始尝试的内容。这可能是完全错误的......我不知道?
我不知道如何进行下一个串联,并且不确定如何正确地进入下一行。
Sub test2()
Dim var As Integer
Dim concat As String
concat = Range("E2").Value & Range("F2").Value
var = 1
'make d2 activecell
Range("D2").Select
Do Until concat = ""
'if the concat is the same as the row before we give it the same number
If concat = concat Then
var = var
Else
var = var + 1
End If
ActiveCell.Value = var
ActiveCell.Offset(0, 1).Select
'make the new concatination of the next row?
Loop
End Sub
感谢任何帮助,谢谢。
最佳答案
尝试一下下面的代码,我添加了一个循环,该循环针对 E
列中的每个单元格执行。它检查 concat 值是否与上一行中的 concat 值相同,然后将 id 写入 D
单元格。
Sub Test2()
Dim Part1 As Range
Dim strConcat As String
Dim i As Long
i = 1
With ThisWorkbook.Worksheets("NAME OF YOUR SHEET")
For Each Part1 In .Range(.Cells(2, 5), .Cells(2, 5).End(xlDown))
strConcat = Part1 & Part1.Offset(0, 1)
If strConcat = Part1.Offset(-1, 0) & Part1.Offset(-1, 1) Then
Part1.Offset(0, -1).Value = i
Else
i = i + 1
Part1.Offset(0, -1).Value = i
End If
Next Part1
End With
End Sub
关于vba - 使用 VBA 将唯一编号添加到 Excel 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34872064/