首页 > 解决方案 > VBA Excel - 生成 ID

问题描述

所以,我正在尝试生成一些学生的 ID,但我很难用它。如果我如何自动生成学生证,有人可以帮助我吗?

这就是我的想法:

事情是:

  1. 当学生的数据存储在工作表中时,我正在使用工作表UserForm中可访问的。HOMESTUDENTS_INFO
  2. 有些学生的 ID 格式不一样。这意味着如果学生来自高级幼儿园级别,则用户可以输入一组新的学生ID。对于 Nursery 或 Junior,格式为NS0000000. 但是,对于高级 Kinder,格式将是402840000.

任何帮助表示赞赏!

标签: excelvba

解决方案


所以你正在寻找的基本上是一种在列中找到最后一个非空单元格的方法,然后在你进入下一个学生ID之前添加一个数字?

假设您的学生证是有序的,只需获取最后一个值。假设所有学生 ID 都以 NS 开头,取其中的一个子字符串,将其变成一个整数,然后将其加 1。我会将文本格式化为保留所有前导零和 NS 值。执行此操作的 Excel 公式是=TEXT("NS", "")&TEXT(yourNumber, "0000000")

应用这个并假设你的学生证从 B2 单元格开始

Sub makeNewID()
    ' Get all student IDs
    Dim studentIDsRange As Range
    Set studentIDsRange = Sheets("STUDENT_INFO").Range("B2", Sheets("STUDENT_INFO").Range("B2").End(xlDown))
    Dim nurseryJuniorIDs As Range
    Set nurseryJuniorIDs = Range("B2") ' Choose whatever top cell you want here, it just can't be an empty cell
    Dim cell As Range
    For Each cell In studentIDsRange
    
        ' If NS is in cell, add to your range
        Debug.Print InStr(1, cell.Value, "NS")
        
        If InStr(cell.Value, "NS") > 0 Then
            If Not cell Is Nothing Then
                ' Add all the cells to new range
                Set nurseryJuniorIDs = Union(nurseryJuniorIDs, cell)
            Else
                ' Add just the first cell to range
                Set nurseryJuniorIDs = cell
            End If
        End If
    Next
    ' Get last student at the bottom from all students
    
    Dim lastStudentIDRange As Range
    'Debug.Print nurseryJuniorIDs.Cells.Count
    Set lastStudentIDRange = nurseryJuniorIDs.End(xlDown) ' Range of the last cell
    'Debug.Print lastStudentIDRange.Value
    ' Get the number after the NS in that students ID
    
    'Debug.Print Replace(CStr(lastStudentIDRange.Value), "NS", "")
    
    Dim lastStudentIDNumber As String
    
    lastStudentIDNumber = Replace(CStr(lastStudentIDRange.Value), "NS", "") ' Get number without "NS"
    'Debug.Print lastStudentIDNumber
    ' Now increment that number
    Dim newStudentIDNumber As Long
    newStudentIDNumber = CLng(lastStudentIDNumber) + 1
    'Debug.Print CStr(newStudentIDNumber)
    ' Finally set the new student ID number into the spreadsheet underneath the last one
    Sheets("STUDENT_INFO").Range("B" + CStr(studentIDsRange.Rows.Count + 2)).Formula = "=TEXT(""NS"", """")&TEXT(" + CStr(newStudentIDNumber) + ", ""0000000"")"
End Sub

对不起,它太冗长了,每一步似乎都是多余的,我知道这段代码可以更短,但我决定让它更容易理解

编辑:我在循环中添加了嵌套的 if 语句For Each,以仅查找具有“NS”的单元格,在处理工作表时,只需在直接Range("B1")调用前面加上Sheets("STUDENT_INFO"). 我的脚本仍将新 ID 一直添加到列表底部,因此虽然数字会递增,但 ID 格式不会。要更改它,只需更改最后一行以在找到的最后一个“NS”单元格下方插入一个新行,然后在此处添加您的值

编辑#2:这个脚本完全适用于我的测试用例,其中我有一列随机 ID,有些则没有,我之前的代码有太多错误,很抱歉,我应该使用CLng而不是CInt因为数字远远超出100000 范围在某一点,但现在一切正常。


推荐阅读