簡體   English   中英

將SQL查詢條件應用於VBA中的多個列

[英]Apply SQL query condition to multiple columns in VBA

請找到我下面的示例表,如果有條件,我要在其中應用數值數據。

在此處輸入圖片說明

查詢碼

sql_string = "Select [Sheet5$].[num] * IIf(([Sheet5$].[to]-[Sheet5$].[frm])<365, .4," & _
"IIf(([Sheet5$].[to]-[Sheet5$].[frm])>365, 1, 0)) from [Sheet5$]"

上面的代碼將幫助我將條件應用於一列即僅num。但是我想將其應用於20-30列左右的多列中,這在我的實際數據中是可用的。可以提到列名,但不是可以將上述if條件寫入每列。 請同樣指導我。

你的意思是這樣嗎?

Public Sub test()
Dim sql_string As String
Dim sheet_name As String

    sheet_name = "Sheet5$"

    sql_string = "Select "
    sql_string = sql_string & GetField(sheet_name, "num") & ","
    sql_string = sql_string & GetField(sheet_name, "num1") & ","
    sql_string = sql_string & GetField(sheet_name, "num2") & ","
    sql_string = sql_string & GetField(sheet_name, "num3")
    sql_string = sql_string & " from [" & sheet_name & "]"

    Debug.Print sql_string

End Sub

Public Function GetField(ByVal sheet_name As String, ByVal fieldName As String)

    GetField = "[" & sheet_name & "].[" & fieldName & "] * IIf(([" & sheet_name & "].[to] - [" & sheet_name & "].[frm]) < 365, 0.4, IIf(([" & sheet_name & "].[to] - [" & sheet_name & "].[frm]) > 365, 1, 0))"

End Function

結果:

Select [Sheet5$].[num] * IIf(([Sheet5$].[to] - [Sheet5$].[frm]) < 365, 0.4, IIf(([Sheet5$].[to] - [Sheet5$].[frm]) > 365, 1, 0)),
    [Sheet5$].[num1] * IIf(([Sheet5$].[to] - [Sheet5$].[frm]) < 365, 0.4, IIf(([Sheet5$].[to] - [Sheet5$].[frm]) > 365, 1, 0)),
    [Sheet5$].[num2] * IIf(([Sheet5$].[to] - [Sheet5$].[frm]) < 365, 0.4, IIf(([Sheet5$].[to] - [Sheet5$].[frm]) > 365, 1, 0)),
    [Sheet5$].[num3] * IIf(([Sheet5$].[to] - [Sheet5$].[frm]) < 365, 0.4, IIf(([Sheet5$].[to] - [Sheet5$].[frm]) > 365, 1, 0)) from [Sheet5$]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM