美文网首页
VBA之数据库操作

VBA之数据库操作

作者: 飞天小澈澈 | 来源:发表于2018-09-14 12:03 被阅读0次
    1. 连接sqlserver
    Sub sqlconnect(myIP As String, myDATA As String, myUSER As String, myPWD As String, Optional sqlstr As String = "", Optional sh As Worksheet = Nothing, Optional rng As Range = Nothing)
        On Error GoTo line
        rng = sh.Range((rng.Address))
        With sh
            Dim cn As Object, rs As Object, i As Integer
            Set cn = CreateObject("ADODB.Connection")
            Set rs = CreateObject("ADODB.Recordset")
            cn.Open "provider=sqloledb;server=" & myIP & ";database=" & myDATA & ";uid=" & myUSER & ";pwd=" & myPWD
            If sqlstr = "" Or rng Is Nothing Or sh Is Nothing Then
            Else
                rs.Open sqlstr, cn, 1, 1
                If rs.EOF Then
                    rs.Close
                    cn.Close
                    Exit Sub
                Else
                    .Cells.ClearContents
                    For i = 1 To rs.Fields.Count
                        Cells(1, i) = rs.Fields(i - 1).Name
                    Next i
                    rng.CopyFromRecordset rs
                    rs.Close
                    cn.Close
                End If
            End If
            Exit Sub
    line:
            MsgBox "数据库连接错误!"
        End With
    End Sub
    

    相关文章

      网友评论

          本文标题:VBA之数据库操作

          本文链接:https://www.haomeiwen.com/subject/bqcogftx.html