我有一个包含多个有价值字段的表格,如下所示: 在表单中,我想让用户在文本框中输入NCR_Num,然后使用VBA进行一些输入验证,然后将其添加到" text_Pool"如下图所示:
此Text_Pool具有NCR_Num作为控制源,因此如果添加或删除了NCR编号,它将自动更新NCR_Num字段。
我不太确定如何处理这种数据类型。 在VBA中,我无法从Text_Pool中获取值,因为我认为我需要将其视为数组或记录集
以下是我尝试记录集尝试的示例,但显然我对我正在做的事情感到很困惑:
Public Function get_NCR_Num(SCAR_Num As Integer) As Integer()
Dim dbsMain As DAO.Database
Dim rstMain As DAO.Recordset
Dim childRS As Recordset
Dim sSearchField, sCriteria As String
Set dbsMain = CurrentDb
Set rstMain = dbsMain.OpenRecordset("tbl_SCAR", dbOpenDynaset, dbReadOnly)
Set childRS = rstMain!NCR_Num.Value
sSearchField = "[SCAR_Num]"
sCriteria = sSearchField & " = " & [SCAR_Num]
With rstMain
.MoveLast
.FindFirst (sCriteria)
With childRS
Do While (Not .EOF)
MsgBox (childRS!NCR_Num.Value)
.MoveNext
Loop
End With
End With
rstMain.Close
dbsMain.Close
Set rstMain = Nothing
Set dbsMain = Nothing
End Function
任何帮助将不胜感激!
答案 0 :(得分:1)
我误解了您的问题,并使用以下代码更新了答案。这应该做你想要的。替换子程序中的代码" Command_LinkNCR_Click'以下内容。 这将:(a)验证nbr存在; (b)如果不在场则加入; (c)如果存在则删除;
警告!此代码仅解决您尝试克服的一个问题。但是,它会对您在表单上查看的记录集进行更新,因此如果您的表单“肮脏”,则可能会出现问题。
尝试一下,如果您有疑问,请告诉我。
Private Sub Command_LinkNCR_Click() Dim dbs作为DAO.Database Dim rsMain作为DAO.Recordset Dim rsChild作为DAO.Recordset Dim strSQL As String Dim blnMatch As Boolean
If IsNull(Me.Text_NCR) Or Me.Text_NCR = "" Then
MsgBox "No value entered for NCR_Num", vbOKOnly, "Missing Value"
Exit Sub
End If
blnMatch = False
Set dbs = CurrentDb
' Only need to work on the current record
strSQL = "select * from tbl_SCAR where SCAR_Num = " & Me!SCAR_Num & ";"
Set rsMain = dbs.OpenRecordset(strSQL, dbOpenDynaset)
If rsMain.EOF Then
' Should never happen
Else
Set rsChild = rsMain!NCR_Num.Value
If rsChild.EOF Then ' If no values yet, add this new one
MsgBox "Add item"
Else
Do While Not rsChild.EOF
' See if we have a match...
If Int(rsChild.Fields(0)) = Int(Me.Text_NCR) Then
blnMatch = True
rsChild.Delete ' Delete item
Exit Do
End If
rsChild.MoveNext
Loop
If blnMatch = False Then ' Need to Add it
rsMain.Edit
rsChild.AddNew
rsChild.Fields(0) = Me.Text_NCR
rsChild.Update
rsMain.Update
End If
End If
End If
'rsChild.Close
rsMain.Close
dbs.Close
Set rsMain = Nothing
Set rsChild = Nothing
Set dbs = Nothing
Me.Refresh
End Sub