应用程序将Excel工作表连接到Access

时间:2017-07-17 09:27:54

标签: excel-vba access-vba vba excel

我被困在下面提到的情况指导我。我有一个用excel制作的用户表单。我可以尝试执行crud我已完成插入。我可以尝试更新或删除不工作请给我一些想法。 这是我的插入代码,它正常工作

insert:-
Private Sub CommandButton1_Click()
   Dim cn As Object
    Dim strQuery As String
    Dim Name As String
    Dim City As String
    Dim myDB As String
    Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
    'Initialize Variables
    Name = Me.TextBox1.Value
    City = Me.TextBox2.Value
    Dept = Me.ComboBox1.Value
    myDB = "C:\Users\abc\Desktop\nis\ni2\em.accdb"
   'Set cn = CreateObject("ADODB.Connection")
With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
        MsgBox "con created"
    End With
     strQuery = "INSERT INTO emp ([Name], [City],[Dept]) " & _
               "VALUES (""" & Name & """, """ & City & """,""" & Dept & """); "
MsgBox "success fully insert"
    cn.Execute strQuery
    cn.Close
    Set cn = Nothing
    Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.ComboBox1.Value = ""
End Sub
update code:-
Dim cn As Object
    Dim strQuery As String
    Dim Name As String
    Dim City As String
    Dim myDB As String
    Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
    'Initialize Variables
'    Name = Me.TextBox1.Value
'    City = Me.TextBox2.Value
'    Dept = Me.ComboBox1.Value
     myDB = "C:\Users\abc\Desktop\nis\ni2\em.accdb"
   'Set cn = CreateObject("ADODB.Connection")
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
        MsgBox "con created"
    End With
     strQuery = "Update emp Set  [Name]='" & Me.TextBox1.Value & "',"&[City]='" & TextBox2.Value & "',&[Dept]='" & Me.ComboBox1.Value & "'"
MsgBox "success fully insert"
    cn.Execute strQuery
    cn.Close
    Set cn = Nothing
    Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.ComboBox1.Value = ""
End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

你的行

  strQuery = "Update emp Set  [Name]='" & Me.TextBox1.Value & "',"&[City]='" & TextBox2.Value & "',&[Dept]='" & Me.ComboBox1.Value & "'"

正在尝试使用这些值更新emp表中的所有行。我怀疑你只想更新一行。您需要添加WHERE子句以指定哪一行。

编辑:注意到该行中的语法错误也是如此。它应该读

 strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "', [City]='" & TextBox2.Value & "',[Dept]='" & Me.ComboBox1.Value & "' Where "

然后应该用你的where子句

结束