2017-07-03 49 views
0

這是我使用MS Access做的一個例子。我有一個包含人名和兩個文本字段的表格用於添加電話號碼。我創建了一個名稱列表框。我設法從列表框中插入選定的姓名,並將電話號碼從文本字段(Tel1和Tel2)插入表格(ContactTable)。我使用瞭如下所示的腳本。如何更改此腳本以使用組合框而不是列表框。MS Access:從組合框中插入一個選定的條目到表

Private Sub ListBoxEnter_Click() 

    Dim Name As String 
    Dim Tel1 As Integer 
    Dim Tel2 As Integer 

    If ListBox.ItemsSelected.Count = 1 Then 
     Name = ListBox.Value 
     Tel1 = Tel1field 
     Tel2 = Tel2field 

     values = "VALUES (" 
     values = values & "'" & Person_Id & "','" & Name & "','" & Tel1 & "','" & Tel2 & "')" 

     SQL = "INSERT INTO ContactTable (Person_Id, Name, Tel1, Tel2)" 
     SQL = SQL & values 
     DoCmd.RunSQL SQL 
     Me.Tel1.Value = Null 
     Me.Tel2.Value = Null 
    End If 

End Sub 

回答

1

與組合框只需更換:

Private Sub ListBoxEnter_Click() 

    Dim Name As String 
    Dim Tel1 As Integer 
    Dim Tel2 As Integer 

    If Not IsNull(Me!ComboBox.Value) Then 
     Name = Me!ComboBox.Value 
     Tel1 = Tel1field 
     Tel2 = Tel2field 

     values = "VALUES (" 
     values = values & "'" & Person_Id & "','" & Name & "','" & Tel1 & "','" & Tel2 & "')" 

     SQL = "INSERT INTO ContactTable (Person_Id, Name, Tel1, Tel2)" 
     SQL = SQL & values 
     DoCmd.RunSQL SQL 
     Me.Tel1.Value = Null 
     Me.Tel2.Value = Null 
    End If 

End Sub 

,如果你有在下拉列表兩列:

FirstName = Me!ComboBox.Value  ' The bound column, often column 0. 
LastName = Me!ComboBox.Column(1) ' The second/other column 
+0

非常感謝古斯塔夫! – cbebgis

+0

對不起,如果我想把名字分成兩個字段名字和姓氏,我是否需要創建兩個組合框/列表框的第一個和最後一個名字或一個組合框/列表框與2列是好的。我如何使用「Name = ListBox.Value」將第一個和最後一個名稱字段添加到ContactTable ?. – cbebgis

+0

是的,您可以在組合框中有兩列或更多列。見編輯的答案。 – Gustav

相關問題