将SQL输出存储在vba变量中

时间:2018-08-16 21:10:12

标签: sql-server excel-vba

我有一个SQL查询,我想将其存储在vba变量中,然后获取输出的行数。

我有以下内容:

Dim PortInfo As Variant
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim lStr As String

Dim LastRow     As Long

  strServer = "DB-01"
    ConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";" & _
                  "Integrated Security=SSPI;"
    cnn.Open ConnectionString

lStr = "SELECT [PORTINFOID],[PORTNAME] FROM [a].[dbo].[portinfo]"

rst.Open lStr, cnn

 If Not rst.EOF And Not rst.BOF Then
   For i = 0 To rst.Fields.Count - 1
      PortInfo = PortInfo & rst.Fields(i).name & vbTab
           Next
       Do Until rst.EOF

      For i = 0 To rst.Fields.Count - 1
      PortInfo = PortInfo & rst.Fields(i) & vbTab
           Next
             rst.MoveNext
    Loop
 End If
 rst.Close
MsgBox PortInfo
    LastRow = ???

通过以上操作,我得到以下信息:

enter image description here

首先,我不确定PortInfo变量是否应为Variant。而且如果应该的话,如何使输出以列/行的方式显示,以便获得结果表的行数。

1 个答案:

答案 0 :(得分:2)

一些建议:

  • PortInfo变量的类型可以为String
  • 在连接字符串中使用服务器名称时,strServer变量已过时。
  • 数据库也可以是连接字符串的一部分。
  • 使用vbTab作为列分隔符时,请使用vbCrLf作为行分隔符。
  • 要计算行数,只需为每条记录增加LastRow变量。
  • 声明变量时请勿使用New,因为这些变量无法清除。
  • 最后清除对象变量。
  • 在每个模块中使用Option Explicit来强制自己声明所有变量(例如i)。

例如,代码可能如下所示:

Dim PortInfo As String
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim lStr As String
Dim LastRow As Long
Dim i As Integer

ConnectionString = "Provider=SQLOLEDB;Data Source=DB-01;" & _
    "Initial Catalog=a;Integrated Security=SSPI;"
lStr = "SELECT [PORTINFOID],[PORTNAME] FROM [dbo].[portinfo]"

Set cnn = New ADODB.Connection
cnn.Open ConnectionString

Set rst = New ADODB.Recordset
rst.Open lStr, cnn

With rst
    If Not .EOF And Not .BOF Then
        For i = 0 To .Fields.Count - 1
            PortInfo = PortInfo & .Fields(i).Name
            If i < .Fields.Count - 1 Then
                PortInfo = PortInfo & vbTab
            Else
                PortInfo = PortInfo & vbCrLf
            End If
        Next
    End If

    Do Until .EOF
        LastRow = LastRow + 1
        For i = 0 To .Fields.Count - 1
            PortInfo = PortInfo & .Fields(i)
            If i < .Fields.Count - 1 Then
                PortInfo = PortInfo & vbTab
            Else
                PortInfo = PortInfo & vbCrLf
            End If
        Next
        rst.MoveNext
    Loop

End With

rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing

MsgBox PortInfo
MsgBox "This have been " & LastRow & " records.", vbInformation, "I'm done."