我正在製作一個簡單的表格來填充表格。其中一個字段是包含一些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. 解析MS Access中的文本
- 2. 使用VBA將VBA代碼添加到MS Access用戶窗體
- 3. 使用VBA解析MS Word文檔中的文本
- 4. MS Access VBA反向地址解析器
- 5. 使用VBA模塊在Access中從窗體獲取文本值
- 6. MS Access窗體 - 在
- 7. MS Access VBA啓用/禁用文本框
- 8. ms Access窗體子窗體排序
- 9. MS Access VBA使用AbsolutePosition
- 10. 的MS Access VBA
- 11. 在Access VBA中解析txt文件
- 12. MS Access窗體不是從
- 13. MS Access窗體調試
- 14. 連續窗體(ms Access 2003)
- 15. 用於自動調整MS Access 2003窗體中控件/子窗體大小的VBA腳本?
- 16. MS ACCESS vba - error
- 17. 使用Windows API在窗體中使用Ms Access淡入淡出
- 18. 使用MS Access獲取Windows窗體中登錄的用戶
- 19. MS Access:如何引用導航窗體的子窗體?
- 20. 的MS Access富文本的文本框從VBA
- 21. 如何從MS Access窗體執行VBA功能?
- 22. 的MS Access VBA導入文本文件中
- 23. 使用VBA的MS Access打印報告
- 24. 的MS Access VBA使用IN操作符
- 25. Access中的複雜文本解析
- 26. VBA文本文件解析
- 27. MS Access 2007使用VBA打開獨立窗體到特定記錄
- 28. 刪除MS Access窗體上的標籤
- 29. 的MS Access - 隱藏列在窗體
- 30. 的MS Access窗體,在表單視圖
你可以使用一個零寬度,零高度的文本框用於每個段和查找這些使它變得容易,或者看看使用split函數,這將通過分隔符分割到一個數組。 –
我需要一個如何使用表單中的數據從外部表中提取數據的想法。 – Ubertwink
這不是你的問題,但答案是dlookup,並嘗試從表格,綁定控件等表格搜索數據。 –