我正在使用VBA打开ODBC连接并检索数据。我有一些SQL查询填充了我需要的内容:
SELECT
tbl.a AS test1
tbl.b AS test2
tbl.c AS test3
FROM
db.tbl AS tbl
INNER JOIN db.more AS more
ON more.a = tbl.a
有没有办法可以在VBA中输入此查询,以便保留其结构并且看起来可读?我这样做了:
Dim sql AS string
sql = ""
sql = sql & "SELECT"
sql = sql & " tbl.a AS test1"
sql = sql & " tbl.b AS test2"
sql = sql & " tbl.c AS test3"
sql = sql & "FROM"
sql = sql & " db.tbl AS tbl"
sql = sql & "INNER JOIN db.more AS more"
sql = sql & " ON more.a = tbl.a"
这对我来说并不是很好看,因为这是我能做到的最好的事情。我只是想看看是否有更好的方法。
答案 0 :(得分:2)
这有帮助吗?
Sub test()
Dim sql As String
sql = "SELECT " & _
"tbl.a AS test1 " & _
"tbl.b AS test2 " & _
"tbl.c AS test3 " & _
"FROM " & _
"db.tbl AS tbl" & _
"INNER JOIN db.more AS more" & _
"ON more.a = tbl.a"
End Sub
答案 1 :(得分:2)
这只是偏好,但也许这个?
sql = "SELECT" + _
" tbl.a AS test1" + _
" tbl.b AS test2" + _
" tbl.c AS test3" + _
"FROM" + _
" db.tbl AS tbl" + _
"INNER JOIN db.more AS more" + _
" ON more.a = tbl.a"
另一种选择是将SQL输入工作表中的单元格,然后 HIDE 该工作表,然后在VBA中使用:
sql = Worksheet("NameOfHiddenWorkSheet").Range("A1").Value
根据我的需要,我通常将工作表命名为“设置”并命名范围(范围名称)
然后你可以这样称呼它:
sql = Sheets("Settings").Range("Sql").Value