【发布时间】:2020-01-31 19:17:19
【问题描述】:
我正在尝试使用 Excel 中的用户表单在访问数据库中附加/更新某个记录。我将表从访问数据库导入到列表框,然后当双击行时,它将条目复制到文本框,这不会失败。但是,当我更改框中的值时,应该会在单击附加按钮时更新/附加数据库中的记录。但是,它没有。
Private Sub cmdAppend_Click()
'Declaring the necessary variables.
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rs As ADODB.Recordset 'dim the ADO recordset class
Dim i As Integer
Dim X As Integer
Dim varr As String
'add error handling
On Error GoTo errHandler:
If Me.Arec36.Value = "" Then
MsgBox "You must enter Child Case.", _
vbOKOnly Or vbInformation, "Insufficent data"
Exit Sub
End If
Set cnn = New ADODB.Connection ' Initialise the collection class variable
varr = Me.Arec36
'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "\\10.4.1.62\RiskTeam\Dispute Core Team Original\Chimp Change\Analysis\Database\ChimpDB.accdb"
Set rs = New ADODB.Recordset 'assign memory to the recordset
'Create the SQL statement to retrieve the data from table.
rs.Open "SELECT * FROM tbl_raw " & _
"WHERE Child_Ref = " & varr, ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdText
If rs.EOF And rs.BOF Then
'Close the recordet and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'In case of an empty recordset display an error.
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
With rs
For i = 22 To 35
rs(Cells(1, i).Value) = Me.Controls("Arec" & i).Value
Next i
rs.Update
End With
'clear the userform values
For X = 22 To 35
Me.Controls("Arec" & X).Value = ""
Me.Arec36.Value = ""
Me.Arec37.Value = ""
Next
'Close the recordset and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'refresh the listbox
ImportUserForm
'Enable the screen.
Application.ScreenUpdating = True
Me.lstDataAccess.RowSource = "DataAccess"
'Inform the user that the macro was executed successfully.
MsgBox "Congratulation the data has been appended", vbInformation, "Append successful"
'error handler
On Error GoTo 0
Exit Sub
errHandler:
'clear memory
Set rs = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Append_Data"
End Sub
【问题讨论】:
-
您是否已逐步确认您的记录集实际上正在获取数据?您的任何消息框提示是否触发?请注意,即使 RS 确实返回数据,您也只会更新 1 条记录。
-
嗨,迈克,列表框显示了整条记录,我可以从中选择。当我选择它时,它会将详细信息放在为他们提供的文本框中的记录中。使用相同的文本框,我应该能够附加/编辑数据。这就是我现在所处的位置。
-
根据您对以下答案的评论,您是否一直收到错误“记录集中没有记录”?您是否通过单步执行代码并检查即时窗口或监视窗口中的值来确保正确填充了
varr? -
使用监视窗口,它会在值下显示
out of context,而在类型下显示为空。 -
建议使用
Me.Arec36.Value而不是Me.Arec36,因为您要专门定义要放入变量的内容,而不是依赖默认属性。不确定,但我的猜测是变量没有正确传输。尝试将代码单步执行到varr = Me.Arec36并在即时窗口中使用? Me.Arec36/? Me.Arec36.Value并查看它是否返回值。
标签: excel vba ms-access userform