在Access女士生成随机的字母数字键

在VB脚本上有这个代码

Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim ltr, rNum, AlphaLtrs, selLtr If Not Intersect(Target, Me.Columns(2)) Is Nothing And _ Target.Cells.Count = 1 Then If Target.Value = "" Then AlphaLtrs = "ABCDEFGHIGKLMNOPQRSTUVWXYZ" selLtr = Application.RoundUp(Rnd() * 26, 0) ltr = Mid(AlphaLtrs, selLtr, 1) rNum = Application.RoundUp(Rnd() * 999999, 0) Target.Value = Me.Range("A" & Target.Row) & "-" & ltr & rNum End If End If End Sub 

我需要通过Access女士创build,一般用于库存产品

女士访问表包含此字段

 ID [Primary Key] Product Title [Short text] Type [Short text] SKU [Short text] Image Preview [Attachment] Price [Number] Availability [yes/No] 

我需要的是SKU将自动生成任何新产品的密钥,唯一的关键,可能是在插入一个新的条目时,或者可能是由最初的新条目上的button,键将相同的Excel代码,如Z401374(阿尔法数字),一旦生成不能改变

把它放到一个模块中运行。 你应该得到你所需要的。

 Sub test() Dim s As String * 7 'fixed length string with 7 characters Dim n As Integer Dim ch As Integer 'the character For n = 1 To Len(s) 'don't hardcode the length twice Do ch = Rnd() * 127 'This could be more efficient. '48 is '0', 57 is '9', 65 is 'A', 90 is 'Z', 97 is 'a', 122 is 'z'. Loop While ch < 48 Or ch > 57 And ch < 65 Or ch > 90 And ch < 97 Or ch > 122 Mid(s, n, 1) = Chr(ch) 'bit more efficient than concatenation Next Debug.Print s End Sub 

你可能需要做的就是在你的表上做INNER JOIN(或者从tblProducts WHERE SKU =“上面生成的string”中selectSKU),以确保它不会随机生成两次相同的string。 最终,只要有足够的SKU,就会发生。 如果是这样,只需重新运行发生器,再次testing,直到找不到匹配,然后您知道您有一个独特的SKU。