根据日期和请求数量创建唯一 ID

Creating Unique ID Based on Date, and Number of Requests

我创建了一个电子表格 (Excel 2007),用于跟踪一年中的订单。作为该跟踪的一部分,我需要根据日期和一天内到达的订单数量生成一个唯一标识符。计数每天重置。

例如;

请求 1= 日期:2016 年 2 月 2 日 -> ID # 20160202-01

请求 2 = 日期:2016 年 2 月 2 日 -> ID # 20160202-02

请求 3 = 日期:2016 年 2 月 3 日 -> ID # 20160202-01

由于业务性质,订单以电子邮件格式送达,然后通过用户表单输入到电子表格中。在此用户窗体中,如果请求的日期与上一个条目匹配,我尝试了 If..Then 语句来递增变量 (n)。这行得通,但是只要表单为 运行,(n) 的值就会重置,这意味着我可以获得的最大值是 2。

我认为解决方法在于使 (n) 成为 global/public 变量,但我不知道如何使用 public 变量通过用户窗体访问。有没有人有任何建议或好的参考来解决这个问题?预先感谢您的帮助。

更新:感谢大家的快速反馈。我刚刚有一位同事路过,一时兴起,问她是否有适合我的方法。她告诉我静态变量将是解决这个问题的方法。此修复有所帮助,但不是完美的解决方案。我将 post 相关代码以显示已实施的修复。

Sub CommandButtonSubmitClose_Click()
 Static n As Integer
 Dim ordDate As Date
 Dim ordYear As Integer
 Dim txtYear As String
 Dim txtMonth As String
 Dim txtDay As String
 Dim txtCount As String
 Dim IDnum As String
 Dim prevRow As Long
 Dim LastRow As Long, ws As Worksheet

 'Define variables'
 prevRow = LastRow - 1
 txtYear = reqYear
 txtMonth = Format(month(reqDate), "00")
 txtDay = Format(day(reqDate), "00")  

If ordDate = ws.Range("A" & prevRow).Value Then
 n = n + 1
 Else                    'Determine daily count'
   n = 1
 End If


txtCount = Format(n, "00")

'Create ID Number'

  IDnum = " " & txtYear & "" & txtMonth & "" & txtDay & "-" & txtCount & ""

新问题:如评论中所述,如果关闭电子表格,则不会存储变量。因此,如果当天晚些时候收到订单,计数将被重置,从而导致整个事情变得一团糟。此外,如果混合中有非连续日期,生成器将不起作用。

为什么不使用 sheet 来存储计数器值?

Sub CommandButtonSubmitClose_Click()
    Dim r As Range
    Dim txtCount As String

    'Add 1 to the counter if the day is still the same,
    Set r = ThisWorkbook.Sheets("Var_Sht").Range("A1")
    If r.Value = Date Then
        r.Offset(1, 0).Value = r.Offset(1, 0).Value + 1
    Else
        r.Value = Date
        r.Offset(1, 0).Value = 1
    End If

    txtCount = r.Offset(1, 0).Value

    'the other code in your procedure...

End Sub

显然您需要一个名为 Var_Sht 的 sheet,但您可以使 sheet 非常隐藏,这样您的用户就看不到它。

sheet 将在 A1 中存储日期,在 A2 中存储每日计数器。当代码运行时,如果 A1 中的日期不等于 Date 函数,那么我们知道 A1 中的日期不是今天,因此我们重置计数器并更新 A1 中的日期。

在尝试了一些建议的想法(包括将计数值存储在一个单元格和另一个单元格中 sheet 之后,我选择了一个使用循环来搜索当天收到的订单的方法.使用 For...Next 循环,我 运行 通过每个订单,如果日期与订单日期匹配,则计数 (n) 更新为 1。循环播放完毕后,(n) 将按上述方式使用。如果没有找到其他值,则 (n) 设置为 1。 (n) 的值在循环之前重置为零。谢谢大家的反馈,感谢大家的帮助!

如果有人感兴趣,这里是修复代码:

n = 1
For i = 11 To LastRow
    If ordDate = ws.Range("A" & i).Value Then
     n = n + 1
    End If
 Next i

 txtCount = Format(n, "00")

'Create ID Number'

IDnum = " " & txtYear & "" & txtMonth & "" & txtDay & "-" & txtCount & ""