问题
I have the below VBA
to extract data from the database:
Sub Get_Data_from_DWH ()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=XX.XXX.XXX.XX; DATABASE=bi; UID=testuser; PWD=test; OPTION=3"
conn.Open
strSQL = " SELECT" & _
" product, brand, sales_channel," & _
" country, sales_manager, sales_date, return_date, " & _
" process_type, sale_quantity, return_quantity " & _
" FROM bi.sales" & _
" WHERE sales_date BETWEEN '2020-01-01' AND '2020-06-30' " & _
" AND country IN ('DE', 'US', 'NL') " & _
" ORDER BY FIELD (brand, 'brand_A', 'brand_B', 'brand_C');"
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
This VBA
extracts the data based on the SQL
without any problem.
However, in my original file the VBA
is much bigger and therefore I have to use a lot of new line separators "
and " & _
.
This makes the handling of the SQL
within the VBA
very difficult since the structure is quite confusing.
Therefore I am wondering if there is an alternative that allows you to enter the SQL
without the new line separators.
Something like this:
strSQL = " SELECT
product, brand, sales_channel,
country, sales_manager, sales_date, return_date,
process_type, sale_quantity, return_quantity
FROM bi.sales
WHERE sales_date BETWEEN '2020-01-01' AND '2020-06-30'
AND country IN ('DE', 'US', 'NL')
ORDER BY FIELD (brand, 'brand_A', 'brand_B', 'brand_C'); "
Do you have any idea if this is possible?
回答1:
Definitive answer - It's not possible in VBA, there's no way for the IDE to allow line breaks in a string.
But here's some suggestions:
If you can't create views on the database and just use those, maybe you could directly link to the data source and do queries that way? So you don't have to use VBA to write queries - Excel has great in-built connectivity and you get a MySQL library, just google "connect to mysql database in excel"
If you really want your queries defined as text somewhere else, one thing that might help to neaten your code is to load your strings from another place where you can keep your sql queries in a format you prefer.
You could load them from a VBA module, which would still have split strings but you can call them like StringSQL = Module1.GetQueryOne
and it helps keep the execution code and the SQL strings separate
You could create a method to pull queries from worksheet cells, or maybe keep them in textboxes on a worksheet, then you can use
SqlString = ThisWorkbook.Sheets("Sheet1").Shapes("SqlQuery1").OLEFormat.Object.Text
or even keep them in a text file that accompanies your Excel workbook and load them from there.
来源:https://stackoverflow.com/questions/63841866/avoid-new-line-seperators-in-mysql-query-within-vba-code