VBA之数据库操作

2018-09-14  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读