我正在製作一個簡單的表格來填充表格。其中一個字段是包含一些ID,個人或範圍,如下所示:「65,73,99-114」,逗號和短劃線作爲分隔符。我需要Access來在另一個表中查找這些ID,並將其他列中的一些數據提供到目標表中。這應該在提交表單時完成。 儘管這個任務聽起來很簡單,而且我知道C#和js的一些,但這是我第一次受到VBA的挑戰。我從來沒有處理過這樣的應用程序,我發現這些手冊太模糊和/或偏離主題。基本上,我需要知道從哪些方面入手以及一些常規技巧,但歡迎您提供任何高級幫助。 p.s.進入2016使用VBA解析MS Access窗體中的文本
0
A
回答
3
沒有什麼從編寫一些代碼來「分析」出給定的文本,並創建所需的SQL阻止你。這樣的代碼看起來像C#或VBA並不是真正困難的部分。真正的挑戰是編寫代碼解析出來。 (編寫代碼! - 這個方法與我的C#很相似)。
我只是空氣編碼這個,它看起來工作得很好。此代碼假定所討論的列是數字列(因此每個值周圍都不需要引號)。
的代碼看起來是這樣的:
Function MyWhereRanges(strRanges, strField As String) As String
' take the raganges, and return a where clause
Dim vTokens As Variant
Dim strRa As String ' sql for ranges
Dim strIn As String ' sql for "in" clause
Dim s As Variant
Dim strResult As String ' return value
vTokens = Split(strRanges, ",")
For Each s In vTokens
If InStr(s, "-") Then
' this is a range - append the range
If strRa <> "" Then
strRa = strRa & " and "
End If
strRa = strRa & "(" & strField & " between " & _
Split(s, "-")(0) & " and " & Split(s, "-")(1) & ")"
Else
' append to the "in" clause
If strIn = "" Then
strIn = "(" & strField & " in ("
Else
strIn = strIn & ","
End If
strIn = strIn & s
End If
Next s
If strIn <> "" Then strIn = strIn & ")) "
strResult = strIn
If strRa <> "" Then
If strResult <> "" Then strResult = strResult & " and "
strResult = strResult & strRa
End If
MyWhereRanges = strResult ' return the value
End Function
所以,從調試窗口,您可以鍵入此:
? mywhereranges("5,6,12-13,15-25","InvoiceNum")
從上面的結果是這樣的:
(InvoiceNum in (5,6)) and
(InvoiceNum between 12 and 13) and
(InvoiceNum between 15 and 25)
因此,在一個實際的形式,你可以發佈一個報告或形式是這樣的:
Dim strSQLwhere As String
strSQLwhere = MyWhereRanges(Me.txtBoxRanges, "InvoiceNum")
DoCmd.OpenReport "rptInvoices", acViewPreview, , strSQLwhere
+0
哦,整潔的解決方案。 – Gustav
相關問題
- 1. 使用vba過濾MS Access子窗體
- 2. 解析MS Access中的文本
- 3. 使用VBA將VBA代碼添加到MS Access用戶窗體
- 4. 使用VBA解析MS Word文檔中的文本
- 5. MS Access VBA反向地址解析器
- 6. 使用VBA模塊在Access中從窗體獲取文本值
- 7. MS Access窗體 - 在
- 8. MS Access VBA啓用/禁用文本框
- 9. MS Access 2007 VBA:使用VBA和Chr驗證文本字段()
- 10. 的MS Access VBA - 可以用戶窗體導出爲PDF
- 11. ms Access窗體子窗體排序
- 12. MS Access VBA使用AbsolutePosition
- 13. 的MS Access VBA
- 14. 將MS Access窗體中的文本框設置爲數組?
- 15. 在Access VBA中解析txt文件
- 16. 從MS Access解析VBA中的JSON(美國BLS)
- 17. MS Access窗體不是從
- 18. MS Access窗體調試
- 19. MS Access窗體加載
- 20. MS Access窗體和表格
- 21. 連續窗體(ms Access 2003)
- 22. 使用VBA的MS Access 2000文本框的控制源
- 23. 用於自動調整MS Access 2003窗體中控件/子窗體大小的VBA腳本?
- 24. MS ACCESS vba select
- 25. MS Access 2010 VBA
- 26. MS ACCESS vba - error
- 27. 使用Windows API在窗體中使用Ms Access淡入淡出
- 28. 使用MS Access獲取Windows窗體中登錄的用戶
- 29. MS Access:如何引用導航窗體的子窗體?
- 30. MS Access中,創建一個窗體和子窗體的關係
你可以使用一個零寬度,零高度的文本框用於每個段和查找這些使它變得容易,或者看看使用split函數,這將通過分隔符分割到一個數組。 –
我需要一個如何使用表單中的數據從外部表中提取數據的想法。 – Ubertwink
這不是你的問題,但答案是dlookup,並嘗試從表格,綁定控件等表格搜索數據。 –