首页 > 解决方案 > 将 Excel 导出到 SQL 而不重复值

问题描述

我成功地在 Excel 和 SQL 之间建立了连接,并设法将 Excel 单元格中的记录添加到 SQL 数据库表中,这是我所做的教程:

将数据从 Excel 导出到 SQL Server

我在excel中制作的(注册表单)我制作的 注册表单,我设法制作了一个宏到(注册)按钮以将数据传输到SQL数据库中,这是供参考的代码:

 Sub connect()
    Dim conn As New ADODB.Connection
    Dim iRowNo As Integer
   ' Dim sCustomerId, sFirstName, sLastName As String

    With Sheets("Sheet2")

        'Open a connection to SQL Server
        conn.Open "Provider=SQLOLEDB;Data Source=seshbones\bones;Initial Catalog=fadi;Integrated Security=SSPI;"

        'Skip the header row
        iRowNo = 2

        'Loop until empty cell in CustomerId
        Do Until .Cells(iRowNo, 1) = ""
            Name = .Cells(iRowNo, 1)
            Location = .Cells(iRowNo, 2)
            Age = .Cells(iRowNo, 3)
            ID = .Cells(iRowNo, 4)
            Mobile = .Cells(iRowNo, 5)
            Email = .Cells(iRowNo, 6)

            'Generate and execute sql statement to import the excel rows to SQL Server table
            conn.Execute "insert into dbo.test (Name, Location, Age, ID, Mobile, Email) values ('" & Name & "', '" & Location & "', '" & Age & "', '" & ID & "', '" & Mobile & "', '" & Email & "')"

            iRowNo = iRowNo + 1
        Loop

        MsgBox "Customers imported."

        conn.Close
        Set conn = Nothing

    End With
 me in the table

End Sub

我想制作一个限制代码以不在表中重复相同的用户名,例如,如果客户在 excel 单元格中输入(用户名)并按下(SignUP),则必须有一个检查 SQL 数据库并检查用户名的功能已经使用并拒绝导出和消息框出现“用户已被使用”我希望你明白我的意思。

标签: sql-serverexcel

解决方案


谢谢你们的帮助,我将错误处理程序代码添加到我的项目中,所以如果我的数据库中有重复的记录,它将阻止我的程序关闭并简单地警告用户“用户名已被占用”这是我修复的方法代码 :

子连接()
    Dim conn 作为新的 ADODB.Connection
    将 iRowNo 变暗为整数
   ' 将 sCustomerId、sFirstName、sLastName 作为字符串调暗
 '错误处理程序
在错误转到 ErrHandler 时:
    使用工作表(“Sheet2”)

'Open a connection to SQL Server conn.Open "Provider=SQLOLEDB;Data Source=seshbones\bones;Initial Catalog=fadi;Integrated Security=SSPI;" 'Skip the header row iRowNo = 2 'Loop until empty cell in CustomerId Do Until .Cells(iRowNo, 1) = "" Name = .Cells(iRowNo, 1) Location = .Cells(iRowNo, 2) Age = .Cells(iRowNo, 3) ID = .Cells(iRowNo, 4) Mobile = .Cells(iRowNo, 5) Email = .Cells(iRowNo, 6) 'Generate and execute sql statement to import the excel rows to SQL Server table conn.Execute "insert into dbo.test (Name, Location, Age, ID, Mobile, Email) values ('" & Name & "', '" & Location & "', '" & Age & "', '" & ID & "', '" & Mobile & "', '" & Email & "')" iRowNo = iRowNo + 1 Loop MsgBox "Customers imported." conn.Close Set conn = Nothing End With Exit Sub ErrHandler:MsgBox "Username Already taken" End Sub


推荐阅读