【发布时间】:2020-03-31 16:21:37
【问题描述】:
我是 ADODB 的新手。我希望我的问题不是那么愚蠢。我打开一个从 Excel 表(用户界面)到另一个表(“数据库”)的 ADODB 连接。代码运行完美,但有时更新或插入的数据不会记录在数据库表中。我不知道为什么,也不知道如何检查它以避免它发生。我知道如果我打开数据库表,保存然后关闭,它会再次运行良好。有人知道原因吗?
代码的过程运行良好,Excel VBA调试器没有出现任何错误...然后我发布一些我认为可能存在问题的部分...
Public cn As ADODB.Connection
Public rst As ADODB.Recordset
Public sSQL As String
Public z, OP, Conf, TempoA, Setor As Double
Public FoundAp, FoundPar As Boolean
Private Sub txtCod_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Set cn = New ADODB.Connection
Set rst = New ADODB.Recordset
If Val(Application.Version) <= 11 Then 'Excel 2003 ou anterior
cn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & EstaPasta_de_trabalho.DbPath & ";" & _
"Extended Properties=Excel 8.0;"
Else 'Excel 2007 ou superior
cn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & EstaPasta_de_trabalho.DbPath & ";" & _
"Extended Properties=Excel 12.0 Xml;"
End If
cn.Open
'Instrução Sql:
sSQL = "SELECT * FROM [tb_Db_Ops$] " & _
"WHERE Cod_Apont LIKE " & txtCod & ";"
rst.CursorLocation = adUseServer
rst.Open sSQL, cn, adOpenKeyset, adLockOptimistic, adCmdText
If Not rst.EOF And Not rst.BOF Then
OP = rst!OP
frmApontamento.Visible = True
txtApontA = txtCod.Text
txtOpA = OP
txtEtapa.Text = rst!Etapa
txtDocA = rst!Documento
txtObraA = Mid(rst!Obra, 12)
Setor = CDbl(rst!Setor)
If IsNull(rst!Status) = False Then
Status = rst!Status
End If
If Status = "FINALIZADO" Then
frmMsg.lblMsg.Caption = "OP já finalizada!"
frmMsg.Show
rst.Close
cn.Close
Set rst = Nothing
Set cn = Nothing
Exit Sub
ElseIf Status = "EM EXECUÇÃO" Then
FoundAp = True
FoundPar = False
ElseIf Status = "" Then
FoundAp = False
FoundPar = False
Else
FoundAp = True
FoundPar = True
End If
Else
frmMsg.lblMsg.Caption = "Apontamento NÃO encontrado na Base de Dados! Supervisão notificada! Tente novamente mais tarde!"
frmMsg.Show
Email.ErroBd = True
Email.ErroGrav = False
Email.Proced = "txtCod_Exit"
Call Email_Erros
rst.Close
cn.Close
Set rst = Nothing
Set cn = Nothing
Exit Sub
End If
rst.Close
sSQL = "UPDATE [tb_Apontamentos$] " & _
"SET dt_f = NOW(), dt = NOW() - dt_i " & _
"WHERE Cod_Apont LIKE " & txtApontR & " AND dt_f IS NULL;"
cn.Execute sSQL
Final:
If Not (rst Is Nothing) Then
If rst.State = 1 Then
rst.Close
End If
Set rst = Nothing
End If
If Not (cn Is Nothing) Then
If cn.State = 1 Then
cn.Close
End If
Set cn = Nothing
End If
end sub
它从用户表单文本框中获取一些值。它在 Windows 10 中的 2013 32 位 Excel 版本上运行。Microsoft ActiveX Data Objects 6.1 和 Microsoft ActiveX Data Objects Recordset 6.0 库已激活。接口是.xlsm,数据库是.xlsx
【问题讨论】:
-
有多少用户正在更新您的“数据库”电子表格(让我们明确术语 - Excel 不是“数据库”)?
-
共有 3 个用户
-
Excel 根本不是为此而设计的。我不太清楚它如何处理多用户和
adOpenKeyset的乐观锁定,但我怀疑您需要使用adOpenStatic。 真正的解决方案是使用 Access、SQL Server Express 或其他一些“真正的”数据库作为后端。 -
您的更新声明中有 txtApontR - 假设这是您表单中的一个文本框,您确定它真的像您工作表中的某些内容吗?不同的数据类型,额外的空间。我想知道它是否真的没有匹配
-
是的,我确定。出现此错误时,我亲自输入值并测试,只有当我打开“数据库”,保存并关闭时才会记录数据。它似乎需要某种刷新或类似的东西......