我的EXCEL VBA 中有一段查詢MS SQL語法 (............where ApplyDateTime Between '20120101' and '20121231' and Excuse='特休假'...........),該如何將日期與假別的部分用VBA文字方塊方式輸入日期範圍和假別可查詢出我要的結果?謝謝!
PS:因為在VBA中可以執行SQL語法,查詢資料,所以我想要這段SQL語法在VBA中可以用變數方式去查詢。作者: stillfish00 時間: 2012-12-7 15:09
回復 1#badboy01
因為沒給前後的程式碼 , 假設你這段為字串..........
"......where ApplyDateTime Between '20120101' and '20121231' and Excuse='特休假'......"
'宣告字串變數
Dim sStartDate as string , sEndDate as string
sStartDate = "20120101"
sEndDate = "20121231"
'上面的那段字串改為
"......where ApplyDateTime Between '" & sStartDate & "' and '" & sEndDate & "' and Excuse='特休假'......"作者: badboy01 時間: 2012-12-7 15:38
回復 2#stillfish00
非常感謝大大,我按照大大的方式程式碼改了,但是我想要任意輸入日期範圍該怎麼改呢?我設計兩個輸入文字方塊日期起點TextBox1和日期結束 TextBox2,
我目前VBA語法是將MS SQL查詢資料讀取到EXCEL sheet上,如果按照大大方式是可以讀取,但是我加入TextBox1,TextBox2就有問題了。
-----------------------------------------------------------------------------------------------------------------------------------------------------
Sub 按鈕2_Click() '定義過程名稱
Dim i As Integer, j As Integer, sht As Worksheet 'i,j為整數變數;sht 為excel工作表物件變數,指向某一工作表
Set cn = New ADODB.Connection '定義資料連結物件 ,保存連接資料庫資訊;請先引用ADO
Dim rs As New ADODB.Recordset '定義記錄物件
Dim strCn As String, strSQL As String '字符串變量
Dim sStartDate As String, sEndDate As String '字符串變量
sStartDate = "20120101" <====我改成sStartDate = "TextBox1"
sEndDate = "20121231" <====我改成sEndDate = "TextBox2" 會有錯誤訊息(從字元字串轉換到datetime時轉換失敗)
strSQL = "SELECT ApplyerDeptName,ApplyName,HR10day,sum(HRdays)as UsedDay,(HR10day-sum(HRdays))as UnusedDay FROM afu_form_HR10 inner join TEST on afu_form_HR10.ApplyName=TEST.HR10name where ApplyDateTime Between '" & sStartDate & " 'AND' " & sEndDate & "' and Excuse='特休假' group by ApplyerDeptName,ApplyName,HR10day"
cn.Open strCn '與資料庫建立連接,如果成功,返回連線物件cn
rs.Open strSQL, cn '執行strSQL所含的SQL命令,結果保存在rs記錄集物件中
i = 2
Set sht = ThisWorkbook.Worksheets("sheet1") '把sht指向當前工作簿的sheet1工作表
Do While Not rs.EOF
sht.Cells(i, 1) = rs("ApplyerDeptName")
sht.Cells(i, 2) = rs("ApplyName")
sht.Cells(i, 3) = rs("HR10day")
sht.Cells(i, 4) = rs("UsedDay")
sht.Cells(i, 5) = rs("UnusedDay")
rs.MoveNext
i = i + 1
Loop
rs.Close
End Sub
----------------------------------------------------------------------------------------------------------------------------------------------------作者: stillfish00 時間: 2012-12-7 16:31