如何使用VBA Excel

时间:2018-04-01 19:19:20

标签: sql excel vba ms-access

我搜索了一下,但我尝试的每个代码都无法帮助我找到答案。

我这里有这个代码:

   Sub registrar_banco(nome, sobrenome, endereco, email, telefone, celular)

' exporta informações da planilha ativa para uma tabela para uma database no acess

Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
'     conecta ao banco de dados access
    Set cn = New ADODB.Connection
'    string de conexão
    cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vinyz\Coding\Database11.accdb;"
'     abre o recordset
    Set rs = New ADODB.Recordset
    rs.Open "banco_de_dados", cn, adOpenKeyset, adLockOptimistic, adCmdTable
'     abre todos os records da tabela
'    r = 2 ' primeira linha da planilha
'    Do While Len(Range("A" & r).Formula) > 0
'     repeat until first empty cell in column A
        With rs
            .AddNew ' cria um novo record
            .Fields("Nome") = nome
            .Fields("Sobrenome") = sobrenome
            .Fields("Endereco") = endereco
            .Fields("Email") = endereco
            .Fields("Telefone") = telefone
            .Fields("Celular") = telefone
            .Update
        End With
'        r = r + 1 ' next row
'    Loop
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

它将寄存器添加到Access中的现有数据库。 由于我正在进行客户注册,我只使用Excel作为编程的桥梁,我想将他与Access DB链接。

现在我只能添加寄存器!

如何从DB Access中删除寄存器以及如何在数据库中搜索专有数据,以及如何将Access中的所有信息都带到Excel中。

我在这里测试了这段代码,但无法找到我如何带来独家数据或整个表格的答案,也给我一些错误。

我是SQL的新手,试图学习它,如果有人有一个逐步的教程,我怎么能在Excel中使用Excel它也会有用哈哈哈哈

Sub buscar_banco()
    Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer

''Access database

strFile = "C:\Users\vinyz\Coding\Database11.accdb"

''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel

strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vinyz\Coding\Database11.accdb;"

''Late binding, so no reference is needed

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'Rough idea
intID = Planilha1.[A1]

strSQL = "SELECT * " _
       & "FROM [banco_de_dados] " _
       & "WHERE ID = " & intID

rs.Open strSQL, cn, 3, 3


''Pick a suitable empty worksheet for the results

Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs

''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

这对一篇文章提出了很多问题。你最好分别发布它们。你会得到更快的答案。

与此同时,有许多方法可以做同样的事情,因为我使用的是旧版本(2007年),我可以告诉你...

插入,选择,更新或删除学习SQL所需的记录。从这里开始:https://www.w3schools.com/sql/default.asp

您还可以使用Access查询向导和设计视图了解并复制将SQL代码粘贴到VBA中。

替代SQL语句的快速示例:

"DELETE * FROM Employees WHERE Title = 'Trainee';"

"UPDATE Employees SET ReportsTo = 5 WHERE ReportsTo = 2;"

您可以使用以下内容记录所有记录。

"Select * FROM table_name;"

这里还有一个教程,介绍如何通过菜单(或录制宏)将其全部输入。http://dailydoseofexcel.com/archives/2004/12/13/

以下是我用来选择一些记录以引入城市匹配的VBA代码。

Public Sub RunQuery()
    Dim A As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set A = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\xxxxx\Documents\Northwind 2007.accdb"
    strSql = "SELECT * FROM Employees WHERE City = 'Redmond' OR City = 'Seattle'"
    A.Open strConnection
    Set rs = A.Execute(strSql)
    arr = rs.GetRows

    'now the array arr has the data queried
    ' Write the field names
    For intColIndex = 0 To rs.Fields.Count - 1
        Range("A1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

    firstRow = LBound(arr, 1)
    firstCol = LBound(arr, 2)
    lastRow = UBound(arr, 1)
    lastCol = UBound(arr, 2)

    For i = firstRow To lastRow
      For j = firstCol To lastCol
        Range("A2").Offset(j, i).Value = arr(i, j)
      Next j
    Next i
    ActiveSheet.Columns.AutoFit

    rs.Close
    Set rs = Nothing
    A.Close
    Set A = Nothing
End Sub

这是更新db:

的一个
Public Sub RunQueryUpdate()
    Dim A As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set A = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\xxxxx\Documents\Students.accdb"
    strSql = "UPDATE Students SET Students.Company = 'Testing' WHERE (((Students.[Last Name])='Smith'));"
    A.Open strConnection
    Set rs = A.Execute(strSql)

    Set rs = Nothing
    A.Close
    Set A = Nothing
End Sub

此处的插入内容:

Public Sub RunQueryInsert()
    Dim A As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set A = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\xxxxx\Documents\Students.accdb"
    strSql = "INSERT INTO Students ([Company], [Last Name], [First Name]) VALUES ('Bay City Fun', 'Smith', 'Jan');"
    A.Open strConnection
    Set rs = A.Execute(strSql)

    Set rs = Nothing
    A.Close
    Set A = Nothing
End Sub

这是删除示例:

Public Sub RunQueryDelete()
    Dim A As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set A = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\xxxxx\Documents\Students.accdb"
    strSql = "DELETE FROM Students WHERE Company='Howdy';"
    A.Open strConnection
    Set rs = A.Execute(strSql)

    Set rs = Nothing
    A.Close
    Set A = Nothing
End Sub