【问题标题】:Generate key with sequential numbers in using Excel vba macro使用 Excel vba 宏生成带有序号的密钥
【发布时间】:2016-12-12 21:16:52
【问题描述】:

我想知道是否可以使用 Excel VBA 宏生成序列号。

我有一个文本文件,其中包含这样的一行:

00|?????|AB_20050106_01|||||||||||||||||||||||||||

是否可以使用 Excel VBA 宏来生成序列中的下一项,例如:

  • AB_20050106_01
  • AB_20050106_02
  • AB_20050106_03
  • ...

每当我在 Excel 中按下按钮时?

最终,我想保存一个名称将包含此密钥的新文件,并且我不想覆盖文件。

【问题讨论】:

  • 是的,有可能。 B.T.W 在您的帖子中您有 AB_20050106_01 并且您想使其成为 AJ_20050106_01 ,是 AB 还是 AJ?
  • 哎呀,对不起,应该是AB

标签: vba excel macros


【解决方案1】:

这里有一个关于如何去做的想法。您需要对其进行编辑以完全适合您的需求,但是应该可以解决问题。跨单元格拆分标题; A1B1C1。 IE。 A1 = AA, B1 = 22222222, C1 = 25 并将宏分配给要调用的按钮。

Sub testing1()
Dim Pt1 As String, Pt2 As Long, Pt3 As Long, FinalString As String
'Get ranges from excel
Pt1 = Range("A1").Value
Pt2 = Range("B1").Value
Pt3 = Range("C1").Value

Pt3 = Pt3 + 1
'Increment pt3
If Pt3 = 100 Then
    Pt3 = 0
    Pt2 = Pt2 + 1
    'Increment pt2/pt1
    If Pt2 = 100000000 Then
        Pt2 = 0
        Select Case Len(Pt1)
            Case 1 'char is one letter
            If UCase(Pt1) = "Z" Then
                Pt1 = "AA"
            Else
                Pt1 = Chr(Asc(Pt1) + 1)
            End If    

            Case 2 'char is two letters
            If Right(Pt1, 1) = "Z" Then
                Pt1 = Chr(Asc(Left(Pt1, 1)) + 1) & "A"
            Else
                Pt1 = Left(Pt1, 1) & Chr(Asc(Right(Pt1, 1)) + 1)
            End If
        End Select       
    End If
End If

Pt2s = Format(Pt2, "00000000") 'Make 8 digits
Pt3s = Format(Pt3, "00") 'Make 2 digits
FinalString = Pt1 + "_" + Pt2s + "_" + Pt3s

'Left these in here so you can see what is going on. 
MsgBox Pt1
MsgBox Pt2
MsgBox Pt3
MsgBox FinalString

'Set current vals to cells.
Range("A1").Value = Pt1
Range("B1").Value = Pt2s
Range("C1").Value = Pt3s

'Create File
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\" + FinalString + ".txt", True)
a.WriteLine ("Here is your first line.")
a.Close

End Sub

【讨论】:

    【解决方案2】:

    有几个选项可以跟踪序列,但一种方法是在模块中保留一个私有变量,您可以在其他函数中引用该变量。这适用于索引01-99

    Option Explicit
    
    Const COUNTER_PREFIX As String = "AB_"
    Private m_lngCounter As Long
    
    Sub Test()
        Dim i As Integer
    
        For i = 1 To 100
            Debug.Print GetNextCounterKey(Format(Now, "yyyyMMdd"))
        Next
    
    End Sub
    
    Function GetNextCounterKey(strItem As String) As String
        m_lngCounter = m_lngCounter + 1
        GetNextCounterKey = COUNTER_PREFIX & strItem & "_" & Format(m_lngCounter, "00")
    End Function
    

    【讨论】:

    • 嗨罗宾,最后一个问题,我可以把这个“AB_20050106_”设为固定格式吗,如果有任何变化,比如说 AD_20160506_。我将如何声明这一点,而不仅仅是使用这个 Const COUNTER_PREFIX As String = "AB_20050106_"
    猜你喜欢
    • 1970-01-01
    • 2011-11-22
    • 2011-02-15
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2011-01-05
    • 2012-08-12
    • 2013-07-14
    相关资源
    最近更新 更多