mysql - 在 Ms. Access 中生成随机字母数字 key

标签 mysql database excel ms-access vbscript

通过在 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

我需要通过Ms. Access创建,一般用于库存产品

Ms Access 表包含此字段

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

我需要的是 SKU 将为任何新产品自动生成 key ,唯一 key ,可以在插入新条目时通过表单上的按钮实现,也可以通过最初的新条目实现, key 将与 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 =“上面生成的字符串”中选择 SKU),以确保它不会随机生成相同的字符串两次。最终,只要有足够的 SKU,这就会发生。如果确实如此,只需重新运行生成器并再次测试,直到找不到匹配项,然后您就知道自己拥有唯一的 SKU。

关于mysql - 在 Ms. Access 中生成随机字母数字 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018606/

相关文章:

MySQL数据库迁移丢失数据

java - 创建数据库驱动的 Java 网站的最佳方法?

javascript - 在 jQuery 自动完成中获取动态值

php - 从 Zend Framework 2 在 mysql 中插入 BIT 列

excel - VBA Excel 中的 VBA DateValue() 错误?

javascript - RegEx 在 VBA 和 JavaScript 中的处理方式有何不同?

sql - "No column information was returned"从空 Excel 工作表中选择时出错

php - pdo异常: to many connections

mysql - 通过将两个整数变量与 MySQL 连接来生成新的字符串变量

mysql : How to use a PDO bound paramter within a CASE statement of SELECT query ?