Visual studio Visual Studio VBA Excel加载项从存储过程中获取x列数的数据

Visual studio Visual Studio VBA Excel加载项从存储过程中获取x列数的数据,visual-studio,vba,stored-procedures,add-in,multiple-columns,Visual Studio,Vba,Stored Procedures,Add In,Multiple Columns,我通常使用vba调用SQL存储过程并在excel中显示数据: Dim sqlConnection1 As New SqlConnection("Data Source=[INSTANCE];Initial Catalog=[databasename];User ID=[user];Password=[password];") Dim shXL As Excel.Worksheet shXL = Globals.ThisAddIn.Application.Acti

我通常使用vba调用SQL存储过程并在excel中显示数据:

Dim sqlConnection1 As New SqlConnection("Data Source=[INSTANCE];Initial Catalog=[databasename];User ID=[user];Password=[password];")
         Dim shXL As Excel.Worksheet
        shXL = Globals.ThisAddIn.Application.ActiveSheet
        Dim Str2 As New SqlCommand
        Dim reader As SqlDataReader
        Dim j As Integer

        Str2.CommandText = "[NAME OF PROCEDURE]"
        Str2.Connection = sqlConnection1
        Str2.CommandType = CommandType.StoredProcedure
        reader = Str2.ExecuteReader()
        j = 2
        While reader.Read()
            shXL.Cells(5, j).Value = reader("[NAME OF COLUMN]")
            j = j +1
        End While

        sqlConnection1.Close()
当返回的列数保持不变时,它就工作了


但是我有一个存储过程,它返回x个列,因此代码必须找出我的存储过程返回了多少列,并相应地显示数据

正常;SqlDataReader已获取,它返回当前行中的列数

另一种方法是使用在您的案例中可能有用的方法

Dim dt As Data.DataTable = new Data.DataTable()
dt.Load(reader)
Dim cc As Integer = dt.Columns.Cont 'get the count of columns
Dim rc As Integer = dt.Rows.Count 'get the count of rows
For c = 0 to cc
    For r =0 to rc
        'here extract your data ;)
    Next
Next