VBA – 在子string和范围内查找数字生成器

我在做数字发生器。 我需要一个函数来查找key1的列匹配,然后检查key1和key2是否存在于该列中,如果不存在,则Box2将是001.如果存在,则Box2将是下一个空闲数字。 (见附图更好的理解)

单击“生成”button后,Box2将填入正确的编号。 之后,整个生成的数字被保存到右列中的下一个空行。

数据样本 用户窗体

这是我现在有:

Private Sub CommandButton1_Click() Dim FindRng As Range Dim col As Long Dim wb As Workbook Set wb = Workbooks.Open("U:\DB_DATA\DB_NUMBERS.xlsx") With wb.Sheets("List1") Set FindRng = .Range("A1:ZZ1").Find(What:=Box1.Text, LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False) If Not FindRng Is Nothing Then col = FindRng.Column Else End If End With BoxMain.Value = Box1.Value & "_" & Box2.Value & "_" & Box3.Value & "_" & Box4.Value & "_" & Box5.Value End Sub 

我试图写一些猜测的代码,因为我看不到控件的名称或如何真正生成数字,以及如何控制格式等。另外,我没有源代码,所以我可以debugging和看看有没有其他问题,所以这是我能做的最好的。 如果你能做到这一点,那么很好,如果没有的话,把所有的东西都寄给我,我尽量去适应它

 Private Sub CommandButton1_Click() Dim chk As Boolean Dim FindRng As Range Dim col As Long Dim wb As Workbook Dim ws As Worksheet Set wb = Workbooks.Open("U:\DB_DATA\DB_NUMBERS.xlsx") Set ws = wb.Sheets("List1") With ws Set FindRng = .Range("A1:ZZ1").Find(What:=Box1.Text, LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False) If Not FindRng Is Nothing Then chk = True col = FindRng.Column 'column with key1 value found, now find key2 in cells 'Check if there is any number in the column Dim i As Integer Dim lRow As Integer Dim key2 As String Dim strSequence As String Dim rng As Range key2 = Box3.Text strSequence = "001" 'start with this unless we find a higher number in cells 'find the last row with data in the column lRow = LastRowInColumn(ws, col) 'numbers are written starting from row 2, so if lRow is 2 there is no number and sequence starts from 001 If lRow <= 2 Then strSequence = "001" 'Box2.Text="001" ??? I don't know the name of the textbox for sequence Else 'get the sequence from last row Dim str As String Dim arr() As String For i = 2 To lRow arr = Split(, "_") 'split the values of cells str = Replace(arr(2), Box4.Text, "") If str = key2 Then 'this is a match, check for the sequence If str > strSequence Then strSequence = str End If Next i 'At this point, strSequence should be the last sequence assigned, so we add one strSequence = Format(CInt(strSequence) + 1, "000") Box2.Text = "001" End If Else chk = False MsgBox "key 1 does not exist." End If End With BoxMain.Value = Box1.Value & "_" & Box2.Value & "_" & Box3.Value & "_" & Box4.Value & "_" & Box5.Value End Sub Function LastRowInColumn(Optional sh As Worksheet, Optional colNumber As Long = 1) As Long 'Finds the last row in a particular column which has a value in it If sh Is Nothing Then Set sh = ActiveSheet End If LastRowInColumn = sh.Cells(sh.Rows.Count, colNumber).End(xlUp).Row End Function 

希望这可以解决你的问题,请find这个链接为Excel文件编号generator.xlsm