excel - 关闭用户窗体后如何继续excel工作表中唯一数字的序列?
问题描述
当用户窗体关闭并稍后打开时,我在获取唯一编号(序列号)的序列时遇到问题。首先,当我在用户表单中填写数据时,所有内容都以正确的顺序完美地记录在 Excel 表中;如果我关闭用户表单并通过用新数据填充用户表单来运行代码,则唯一 ID 再次从“1”开始,但不是根据先前保存的 excel 工作表行号。
下面是我试过的代码:
Private Sub cmdSubmit_Click()
Dim WB As Workbook
Dim lr As Long
Set WB = Workbooks.Open("C:\Users\Desktop\Book2.xlsx")
Dim Database As Worksheet
Set Database = WB.Worksheets("Sheet1")
eRow = Database.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
lr = Database.Range("a65536").End(xlUp).Row
With Sheets("Sheet1")
If IsEmpty(.Range("A1")) Then
.Range("A1").Value = 0
Else
Database.Cells(lr + 1, 1) = Val(Database.Cells(lr, 1)) + 1
End If
End With
Database.Cells(eRow, 4).Value = cmbls.Text
Database.Cells(eRow, 2).Value = txtProject.Text
Database.Cells(eRow, 3).Value = txtEovia.Text
Database.Cells(eRow, 1).Value = txtUid.Text
Call UserForm_Initialize
WB.SaveAs ("C:\Users\Desktop\Book2.xlsx")
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim maxNumber
If Not Intersect(Target, Range("B:B")) Is Nothing Then
' don't run when more than one row is changed
If Target.Rows.Count > 1 Then Exit Sub
' if column A in the current row has a value, don't run
If Cells(Target.Row, 1) > 0 Then Exit Sub
' get the highest number in column A, then add 1 and write to the
' current row, column A
maxNumber = Application.WorksheetFunction.Max(Range("A:A"))
Target.Offset(0, -1) = maxNumber + 1
End If
End Sub
Private Sub UserForm_Initialize()
With txtUid
.Value = Format(Val(Cells(Rows.Count, 1).End(xlUp)) + 1, "0000")
.Enabled = False
End With
With txtProject
.Value = ""
.SetFocus
End With
End Sub
在此图像中,如果您看到唯一 ID 重复 1 和 2,但我需要 1、2、3、4....
解决方案
我认为这就是问题的来源。每次用户表单为 时,您都需要重新计算最后一行Initialized
。
Private Sub UserForm_Initialize()
Dim ws as Worksheet: Set ws = Thisworkbook.Sheets("Database")
With txtUid
.Value = Format(ws.Range("A" & ws.Rows.Count).End(xlUp) + 1, "0000")
.Enabled = False
End With
With txtProject
.Value = ""
.SetFocus
End With
End Sub
推荐阅读
- c - 使用 g++ 编译时如何修复 structmember.h 中的错误
- selenium - 如何使用 xpath 匹配 div 元素中的文本?
- php - 当我希望仅在第一个条件为真时才调用函数时,将函数作为 IF 的第二个条件传递是否安全?
- swift - 使用 Perfect-Markdown,表格不会像 GitHub 的 UI 那样呈现
- python - 如何自动化 SARIMA 模型进行时间序列预测?
- python - 在大文件中搜索文本并将结果写入文件
- python - 有条件的 while 循环没有正确反应
- javascript - CheerioJS 和一些抓取问题
- dart - 为什么等待飞镖中的path_provider?
- powershell - 为什么这段代码只输出我做了替换的行?