VBA - 获取Array中的所有值作为后续字符串

时间:2017-06-29 15:16:23

标签: sql arrays vba

我已连接VBA& SQL数据库以拉取信息。 我写了一个脚本,它可以完全返回我想要的内容,但我想让它变得动态(改变使用年限等),我在这里遇到问题。

我需要在我的SQL查询中有一个特殊的行,它只有一行在行之间发生变化(需要更改的行数和y.Date_Year =时的大小写)

我在下面的代码中收到一条错误消息,指出我的“period()”数组正上方的“&”符号中存在类型不匹配。

Sub test()
Dim SQLDB As ADODB.Connection
Dim sQuery As String
Dim info()
Dim Start_D As String
Dim End_D As String
Dim Numerator_Used As String
Dim Denominator_Used As String
Dim Number_Years As Integer
Dim period()

Numerator_Used = Range("Numerator")
Denominator_Used = Range("Denominator")
Start_D = Range("Start_Date")
End_D = Range("End_Date")

Range("A11:J100000").Cells.ClearContents

Number_Years = End_D - Start_D
ReDim period(Number_Years + 1)

For i = 0 To Number_Years
period(i + 1) = ",sum(case when y.date_year = " & Start_D + i & " then n." & Numerator_Used & " end) / sum(case when y.date_year = " & Start_D + i & " then s." & Denominator_Used & " end) as '" & Numerator_Used & "/" & Denominator_Used & " " & Start_D + i & "' & _ "
Next i


' Get Margin Expectation Changes
sQuery ="select m.date_month" & _
        " m.date_month " & _
        period() & _
        " from " & Numerator_Used & " as n" & _
        " inner join " & Denominator_Used & " as s on  s.company_id = n.company_id" & _
                              " and s.date_month_id = n.date_month_id" & _
                              " and s.date_year_id = n.date_year_id" & _
        " inner join date_year as y on y.date_year_id = n.date_year_id" & _
        " inner join date_month as m on m.date_month_id = n.date_month_id" & _
        " where y.date_year between " & Start_D & " and " & End_D & " " & _
        " and n." & Numerator_Used & " <> 0" & _
        " and s." & Denominator_Used & " <> 0" & _
        " group by m.date_month;"

Set rs = Common.SQL_Read(SQLDB, sQuery)


ThisWorkbook.Worksheets("Sheet1").Range("A11").CopyFromRecordset rs

Set SQLDB = Common.SQL_Close(SQLDB)

End Sub

1 个答案:

答案 0 :(得分:0)

正如我在问题的ocmment中提到的,你不能明确地将period()数据转换为字符串,因为它是变量数据类型的数组(每个未定义的变量被视为变体数据类型)。你必须遍历数组数据,即:

For i = LBound(period()) To UBound(period())
    sQuery = sQuery &   period(i) & "...." 
Next
'finally:
sQuery = "SELECT ... " & sQuery & " ...."

如上所述更改代码,让我知道它是否有效。