如何使用excel VBA写入SQL表

时间:2016-11-15 15:10:59

标签: sql-server excel vba excel-vba

我有一个名为Audit的SQL表。该表中有两个字段叫做UN和CN。我的服务器名称是分析性的,DB是DW_ALL。我试图在excel中捕获访问/打开我的工作簿或工作表的用户名和计算机名称,然后将该审计信息写入我的SQL表。

Sub UpdateTable()

Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date

strText = ActiveSheet.Range("b4").Value
''strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy")''

Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
        "Data Source=icl-analive; " & _
        "Initial Catalog=DW_ALL;" & _
        "User ID=ccataldo;" & _
        "Trusted_Connection=Yes;"

cnn.Open cnnstr

''uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & strDate & ")"''
''uSQL = "INSERT INTO Audit (UN,CN) VALUES (MsgBox Environ("username"), MsgBox         Environ("username""''
uSQL = INSERT INTO Audit (UN,CN) VALUES ('MsgBox Environ("username") ', 'MsgBox Environ("username"'))

Debug.Print uSQL

cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub

2 个答案:

答案 0 :(得分:1)

连接字符串可能很棘手。我非常依赖ConnectionStrings.com来刷新我的记忆。

Trusted_Connection和用户ID是互斥的。如果要使用Windows帐户登录SQL Server,请使用可信连接。用户名和密码用于使用SQL account登录。

假设您要使用Windows登录;试试这个:

Provider=SQLNCLI11;Server=analive;Database=DW_ALL;Trusted_Connection=yes;

答案 1 :(得分:0)

以下是写入AccessDB的示例脚本。 SQL应该与所需的vba语句类似。我希望它有所帮助

它也使用DAO而不是Addob连接类型。

Private Sub thisbetheshitmane()
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim tb As DAO.TableDef
    Dim vAr As String
    Dim i As Integer
    Dim y As Integer
    Dim InCombined As Boolean
    Dim InOpen As Boolean
    Dim vbSql As String

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual

    Dim StartTime As Double
    Dim SecondsElapsed As Double

    StartTime = Timer

    Set db = DBEngine.OpenDatabase("C:\Users\dzcoats\Documents\Microsoft.accdb")

    For Each tb In db.TableDefs
        If Len(tb.Connect) > 0 Then
            tb.RefreshLink
        End If
    Next tb     

    Set rst = db.OpenRecordset("SELECT DISTINCT [Table_Name].Defect FROM [Table_Name] WHERE [Table_Name].Defect IS NOT NULL;")

    Dim QResult() As Variant
    QResult = rst.GetRows(rst.RecordCount)
    For a = LBound(QResult, 2) To UBound(QResult, 2)
        vAr = QResult(0, a)
    Next a

    For y = LBound(QResult, 2) To UBound(QResult, 2)
        If vAr <> "Defect" And vAr <> vbNullString And vAr <> "" Then

            If InCombined = True And InOpen = True Then
                vbSql = "UPDATE [Table_Name] SET [Table_Name].Status ='Bad Defect Number' WHERE ((([Table_Name].Defect)='" & vAr & "'));"
                db.Execute vbSql
            End If

            If InCombined = False And InOpen = True Then
                vbSql = "UPDATE [Table_Name] SET [Table_Name].Status ='Completed' WHERE ((([Table_Name].Defect)='" & vAr & "'));"
                db.Execute vbSql
            End If

        End If
    Next y

    rst.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing

Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic

SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub