I support a VBA-Access program (Office 365) which contains tables, queries, forms, reports, modules and class modules to manage customers, patients, as well as accounting. At the end of each year I programmatically create a database accounts of <current year> in which I store only the tables, queries, reports, modules and class modules necessary to display the accounts.
This year I had to abandon my good old computer on Windows 7 for a new one on Windows 11. Alas! The accounts of <current year> database no longer works: it seems to be missing some references, but there is something else, I don't know what.
I use this code to create the database and populate it from the main database:
fileName = CHEMIN_SAUVEGARDE_COMPTE & "FFcompte " & year & ".accdb"
Set appAccess = CreateObject("Access.Application")
appAccess.NewCurrentDatabase fileName
Has anyone come across this problem before?
or is there a method to copy a database and delete some data from it?
with your answers, I have find a solution, thanks. I open a copy of the database that contains the basic tables (the program works on linked tables), I delete the unnecessary tables and data from the new accounting year, I add to it the necessary queries, reports and modules and I save this DB under the name CHEMIN_SAUVEGARDE_COMPTE FF Sàrl compte<exercice>.accdb
' create the db for accounts of current year
retCar = MsgBox("Create the db FF Sàrl compte" & exercice & " ?", vbOKCancel, _
"Clôture de l'exercice comptable")
If retCar = vbOK Then
gNomFichier = CHEMIN_SAUVEGARDE_COMPTE & "FF Sàrl compte " & exercice & ".accdb"
' Create Microsoft Access Workspace object.
Set wrkAcc = CreateWorkspace("", "admin", "", dbUseJet)
Set dbCurrent = wrkAcc.OpenDatabase("C:\FF Sàrl\FF Sàrl données\FF Sàrl Data\FF Sàrl data - copie.accdb", True)
' delete useless tables
With dbCurrent
.TableDefs.Delete "Table des erreurs"
.TableDefs.Delete "tblConversionApexDbf45"
.TableDefs.Delete "tblDetailNoteHandylife"
.TableDefs.Delete "tblExportPaiementPraxo"
.TableDefs.Delete "tblExportPaiementPraxoCopy"
.TableDefs.Delete "TblLocalite"
.TableDefs.Delete "tblNoteHandylife"
.TableDefs.Delete "tblPaiementOrphelin"
.TableDefs.Delete "tblClientService"
.TableDefs.Delete "tblEmployeEnfant"
.TableDefs.Delete "tblNotePaiement"
.TableDefs.Delete "tblOldNotePaiement"
.TableDefs.Delete "tblPatientAdresseFact"
.TableDefs.Delete "tblNotePoursuite"
.TableDefs.Delete "tblPoursuite"
.TableDefs.Delete "tblClientMiseEnCompte"
.TableDefs.Delete "tblCompteBancaire"
.TableDefs.Delete "tblDecompteSalaire"
.TableDefs.Delete "tblDecompteVacances"
.TableDefs.Delete "tblEnfant"
.TableDefs.Delete "tblOfficeJudiciaire"
.TableDefs.Delete "tblPaiement"
.TableDefs.Delete "tblService"
.TableDefs.Delete "tblNote"
.TableDefs.Delete "tblOldNote"
.TableDefs.Delete "tblClientOldPC"
.TableDefs.Delete "tblClientPieceComptable"
.TableDefs.Delete "tblOldPaiement"
.TableDefs.Delete "tblAdresseFact"
.TableDefs.Delete "tblPatient"
.TableDefs.Delete "tblEmploye"
' in tblEcriture and tblDetailEcriture, delete dta of the new year
qryStr = "SELECT distinct tblEcriture.detailRef FROM tblEcriture where tblEcriture.[date Ecriture] > " & FF_dateSQL(dateCloture)
Set qryDef = .CreateQueryDef("", qryStr)
Set recTemp = qryDef.OpenRecordset()
If Not recTemp.EOF Then
recTemp.MoveLast
recTemp.MoveFirst
Set tbldef = .TableDefs("tblDetailEcriture")
qryStr = "SELECT tblDetailEcriture.* FROM tblDetailEcriture"
Set qdfTemp = .CreateQueryDef("", qryStr)
Set recCompte = qdfTemp.OpenRecordset()
recCompte.MoveLast
recCompte.MoveFirst
Do While Not recTemp.EOF
recCompte.FindFirst "[no Detail Ecriture] = " & recTemp!detailref
If Not recCompte.NoMatch Then
recCompte.Delete
recCompte.Requery
End If
recTemp.MoveNext
Loop
End If
' in tbldecompte, delete data of the new year
qryStr = "SELECT tbldecompte.* FROM tbldecompte where tblDecompte.[date conf] > " & FF_dateSQL(dateCloture)
Set qryDef = .CreateQueryDef("", qryStr)
Set recTemp = qryDef.OpenRecordset()
If Not recTemp.EOF Then
recTemp.MoveLast
recTemp.MoveFirst
Do While Not recTemp.EOF
recTemp.Delete
recTemp.MoveNext
Loop
End If
End With
dbCurrent.Close
wrkAcc.Close
FileCopy "C:\FF Sàrl\FF Sàrl données\FF Sàrl Data\FF Sàrl data - copie.accdb", gNomFichier
' copy account queries in the new db
For Each qryDef In CurrentDb.QueryDefs
Select Case qryDef.Name
Case "reqActif", "reqPassif", "reqActifPassif", _
"reqBeneficePerteReporte", "reqBilan", "reqC51", _
"reqC51Stat", "reqC51TVA", "reqCategorie", "reqCompte", _
"reqCompteComplet", "reqCompteDA", "reqCompteEcriture", _
"reqCompteSommeDA", "reqCompteVide", "reqDecompte", "reqDivision", _
"reqEcriture", "reqFactureExt", "reqGroupe", "reqLstComptes", _
"reqNouveauCapital", "reqResultatAvantImpot", _
"reqResultatAvantImpotOld", "reqResultatComptable", _
"reqResultatComptableOld", "reqResultatExp", _
"reqResultatExploitation", "reqResultatExploitationOld", _
"reqResultatHorsExp", "reqResultatOrdinaire", _
"reqResultatOrdinaireOld", "reqStatistiquesAnnuelles", _
"reqStatistiquesMensuelles", "reqStatistiquesParClient", _
"reqStatistiquesSemestrielles", "reqStatTotales"
DoCmd.CopyObject gNomFichier, , acQuery, qryDef.Name
End Select
Next qryDef
' copy account reports in the new db
For Each obj In Application.CurrentProject.AllReports
Select Case obj.Name
Case "rptBilanAnnuel", "rptBilanProvisoire", "rptCloture", _
"rptComptes", "rptCompteVide", "rptPlanComptable", "rptResultat", _
"rptResultatHorsExploitation", _
"rptStatistiquesAnnuelles", "rptStatistiquesMensuelles", _
"rptStatistiquesParClient", "rptStatistiquesSemestrielles", _
"subRptStatistiquesMensuelles", "subRptStatistiquesParClient", _
"subRptStatistiquesSemestrielles"
DoCmd.CopyObject gNomFichier, , acReport, obj.Name
End Select
Next obj
' copy classes 'ValeursFF', 'Compte' et 'client' and module 'UtilitaireCompte' in the new db
DoCmd.CopyObject gNomFichier, , acModule, "ValeursFF"
DoCmd.CopyObject gNomFichier, , acModule, "Compte"
DoCmd.CopyObject gNomFichier, , acModule, "Client"
DoCmd.CopyObject gNomFichier, , acModule, "UtilitaireCompte"
Related
I'm using SQL statement for the fist time in VBA, how can I use the column number of my Excel sheet in a SQL statement?
Below is an example of what I want to do :
"SELECT * FROM [Sheet1$] WHERE 'ColumnNumber4 =" & mySQLVariable
As you see the only thing wrong there is 'ColumnNumber4'
I've already tried this :
"SELECT * FROM [Sheet1$] WHERE [M] =" & mySQLVariable
Where M is the name I have set for the Column Number 4 but this don't work as excepted : my .docx ask me to select a table but the table MUST be selected with the
"SELECT * FROM[Sheet1$] WHERE[M] = " & mySQLVariable
NB : SELECT * FROM[Sheet1$] work :
The excel file is like this :
Before using the macro the docx looks like :
and after it looks like this (Working as excepted)
By deduction i think that WHERE[M] = " & mySQLVariable is the problem
In fact with WHERE I got :
Here is my full code :
Sub Publipostage()
'Nécessite d'activer la référence "Microsoft Word xx.x Object Library"
Dim docWord As Word.Document
Dim appWord As Word.Application
Dim NomBase As String
Dim i As Long
Dim rs As Recordset
i = 3
mySQLVariable = "MyString"
NomBase = "M:\User\Folder\FolderItem.xlsm"
Application.ScreenUpdating = False
Set appWord = New Word.Application
appWord.Visible = True
'Ouverture du document principal Word
Set docWord = appWord.Documents.Open("M:\User\Folder\FolderItem.docx")
MsgBox ActiveCell.Column
Set rs = "SELECT * FROM [Interface-Test$]"
Debug.Print rs(3).Name
'fonctionnalité de publipostage pour le document spécifié
With docWord.MailMerge
'Ouvre la base de données
.OpenDataSource Name:=NomBase, _ Connection:="Driver={Microsoft Excel Driver (*.xlsm)};" & _
"DBQ=" & NomBase & "; ReadOnly=True; ", _
SQLStatement:="SELECT * FROM [Interface-Test$] WHERE [F4] = " & mySQLVariable
'Spécifie la fusion vers l'imprimante
.Destination = wdSendToNewDocument
.suppressBlankLines = True
'Prend en compte l'ensemble des enregistrements
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
'Exécute l'opération de publipostage
.Execute Pause:=False
End With
' Activation du doucment principal de Publipostage et fermeture
docWord.Activate
docWord.Close savechanges:=False
' Affichage l'application Word
appWord.Visible = True
Set docWord = Nothing
Set appWord = Nothing
'Fermeture du document Word
'docWord.Close False
'appWord.Quit
End Sub
Thanks for your time and consideration.
As shown finally by OP, the data range of Excel begins on A2 with column headers in row 2 and data beginning in row 3. In Excel ODBC connections, when specifying SheetName$, by default it assumes data begins in A1 with named columns.
Since this default does not apply, the FROM clause must change accordingly to specify the beginning and end cell. To avoid this specific range requirement, adjust spreadsheet to not use row 1 for non-data items.
SQLStatement:="SELECT * FROM [Interface-Test$A2:P1000] WHERE [MAIL ADDRESS] = " & mySQLVariable
Your question is a little ambiguous but...
If you want to use the column number then you can use [F4] as the identifier. This is what it will default to.
If you want to use the name of the column you have to be sure to have set HDR=YES in your connection string.
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
If you simply want to work out what the name of the fourth column is...
set rs="SELECT * FROM [Sheet1$]"
Debug.Print rs(3).name
Which will give you the name the recordset is using (the field numbers start at zero).
I have a problem connecting my windows mobile application developed using vb.net in my SQL server 2008 as my back end. Here is my connection string :
Data Source=STEPH-PC\SQL2008;Initial Catalog= MyDB; User ID = myusername; Password = mypassword;
It always give me an error that SQL server does not exist or access denied. Any help on how to solve this issue?
1- Testing connection Server versus Pocket PC:
First at all test if your SQL Server CE mobile agent connects to SQL Server CE Server agent. To do this you have to install SQL Server CE 3.5 in the server and in your Pocket PC. Search in google How to install SQL Server CE 3.5. In the process you create a Virtual Directory in Server and in that directory you got a file sqlcesa35.dll, so to test the connection in your Pocket PC browser write: http://ipserver/virtual_directory/sqlcesa35.dll (of course ipserver must be your server IP and virtual_directory must be your virtual directory name). Doing this you have to get in your Pocket PC the message:
Microsoft SQL Server Compact
Server Agent
At this point I have to mention that always you must have internet connection.
2- Retrieving files from the server (this is a sample code, not debugged, I only have taken some parts from other project and put them here).
Function get_companies(ByVal sSucursal As String, ByVal cn_Interface As System.Data.SqlServerCe.SqlCeConnection, _
ByVal cmd_Interface As System.Data.SqlServerCe.SqlCeCommand, ByVal dr_Interface As System.Data.SqlServerCe.SqlCeDataReader) As Boolean
get_companies = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
'The last variable sInternetURL is something like: http://ip_server/virtual_directory/sqlcesa35.dll
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
'sIPSQLServer is the server ip where is running SQL Server
'sBDSQLServer is your DataBase server.
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
'sPath is your directory in your Pocket PC, begings with \
'sDataBase_Interface is the database in my Pocket PC, an .sdf file
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet 'a valid user in your domain
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
Try
'In server database there is a table: Monedas
rda.Pull("_Monedas", "Select Moneda, Descripcion, Abreviada From Monedas Where Sucursal = '" & sSucursal & "'", _
_strRemoteConnect, System.Data.SqlServerCe.RdaTrackOption.TrackingOff)
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Loop
'read the data received, just testing, may be this code not to be here because you process the data outside the function.
Try
cmd_Interface.CommandText = "Select Moneda, Descripcion, Abreviada From _Monedas"
dr_Interface = cmd_Interface.ExecuteReader()
Do While dr_Interface.Read()
messagebox.show("Moneda = " & dr_interface("Moneda") & " - " & dr_interface("Descripcion") & " - " & dr_interface("Abreviada"), _
"Currencies Received", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
Loop
get_companies = true
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cmd_Interface.Dispose()
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
3- Excecuting a sentence in Database Server from your Pocket PC and Transferring data from Pocket to Server:
Function EnviarClientesNuevos(ByVal sSucursal As String, ByVal sZona As String, ByVal sRuta As String) As Boolean
Dim sLineas As String
Dim nRegs As Integer
Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
EnviarClientesNuevos = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
If DropTableE("_NEW_CLIENTES_XX") Then
Try
'_NEW_CLIENTES_XX is a table in your SQL Server (The server, not the Pocket)
rda.Pull("_NEW_CLIENTES_XX", "Select Id, Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta " & _
"FROM _NEW_CLIENTES_XX WHERE Sucursal = ''", _strRemoteConnect, SqlServerCe.RdaTrackOption.TrackingOn)
'In where clause I compare to '' because I only need the structure
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
End If
Loop
Try
'--
cn_Interface = New System.Data.SqlServerCe.SqlCeConnection
cn_Interface.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Interface & ";Password=" & sPassword
cn_Interface.Open()
cmd_Interface = cn_Interface.CreateCommand()
cmd_Interface.CommandType = CommandType.Text
'--
'here I have an open connection to another database in my Mobile Device. Here I have to mention that I work with 2 databases in my mobile device:
'One database for getting the data from server, I only use it when I get data from server and when I send data to server
'and other database which is my main database, the database that is used all the day storing customers transactions.
'here I already have open (outside this function) the connection to this second database, but the sentence are the same above,
'something like this:
'Try
' cn = New System.Data.SqlServerCe.SqlCeConnection
' cn.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Ppal & ";Password=" & sPassword
' cn.Open()
' cmd = cn.CreateCommand()
' cmd.CommandType = CommandType.Text
'Read the data from my main Pocket PC database
cmd.CommandText = "SELECT CodCli, Nombre, Direccion, Ruc, Clase From CLIENTES WHERE CLASE IN ('N', 'M')"
dr = cmd.ExecuteReader()
Do While dr.Read()
'Insert the data in the table structure that I get above.
'remember that this table is in the database that only is used when transferring data, its a temporal database.
cmd_Interface.CommandText = "INSERT INTO _NEW_CLIENTES_XX (Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta) " & _
"VALUES('" & sSucursal & "', '" & sZona & "', " & dr("CodCli") & ", '" & _
dr("Nombre") & "', '" & dr("Direccion") & "', '" & dr("Ruc") & "', '" & _
dr("Clase") & "', '" & sRuta & "')"
nRegs = cmd_Interface.ExecuteNonQuery()
Loop
dr.Close() : dr.Dispose()
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Exit Function
Finally
Try
dr.Close()
dr.Dispose()
Catch ex As Exception
End Try
'If cn.State <> ConnectionState.Closed Then
' cmd.Dispose()
' cn.Close()
' cn.Dispose()
'End If
If cn_Interface.State <> ConnectionState.Closed Then
cmd_Interface.Dispose()
cn_Interface.Close()
cn_Interface.Dispose()
End If
End Try
Do While True
Try
'I excecute a sentence in the Server. I delete the data in _NEW_CLIENTES_XX which is a work table in SQL server.
rda.SubmitSql("Delete From _NEW_CLIENTES_XX Where Sucursal = '" & sSucursal & "' AND Zona = '" & sZona & "' And Ruta = '" & sRuta & "'", _strRemoteConnect)
'I send the data to server
rda.Push("_NEW_CLIENTES_XX", _strRemoteConnect, System.Data.SqlServerCe.RdaBatchOption.BatchingOn)
EnviarClientesNuevos = True
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
Loop
End Function
Generalities:
Function DropTableP(ByVal sTabla As String) As Boolean
'Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
'Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
'Dim dr_Interface As System.Data.SqlServerCe.SqlCeDataReader
Dim nRegs As Integer
Try
'cn_Interface = New System.Data.SqlServerCe.SqlCeConnection("Data Source=" & sPath & "\" & sDataBase_Ppal & "; Password=" & sPassword)
'cn_Interface.Open()
'cmd_Interface = cn_Interface.CreateCommand()
'cmd_Interface.CommandType = CommandType.Text
cmd.CommandText = "Select TABLE_NAME From INFORMATION_SCHEMA.TABLES Where TABLE_NAME = '" & sTabla & "'"
dr = cmd.ExecuteReader()
If dr.Read() Then
dr.Close()
dr.Dispose()
cmd.CommandText = "DROP TABLE " & sTabla
nRegs = cmd.ExecuteNonQuery()
DropTableP = True
Else
dr.Close()
dr.Dispose()
DropTableP = True
End If
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
Sub ShowErrorSqlServerCE(ByVal exc As System.Data.SqlServerCe.SqlCeException)
Dim bld As New System.Text.StringBuilder
Dim err As System.Data.SqlServerCe.SqlCeError
Dim errorCollection As System.Data.SqlServerCe.SqlCeErrorCollection = exc.Errors
Dim errPar As String
Dim numPar As Integer
' Loop through all of the errors.
For Each err In errorCollection
bld.Append(ControlChars.Cr & " Error Code: " & err.HResult.ToString("X"))
bld.Append(ControlChars.Cr & " Message : " & err.Message)
bld.Append(ControlChars.Cr & " Minor Err.: " & err.NativeError)
bld.Append(ControlChars.Cr & " Source : " & err.Source)
' Loop through all of the numeric parameters for this specific error.
For Each numPar In err.NumericErrorParameters
If numPar <> 0 Then
bld.Append(ControlChars.Cr & " Num. Par. : " & numPar.ToString())
End If
Next numPar
' Loop through all of the error parameters for this specific error.
For Each errPar In err.ErrorParameters
If errPar <> [String].Empty Then
bld.Append(ControlChars.Cr & " Err. Par. : " & errPar)
End If
Next errPar
' Finally, display this error.
MessageBox.Show(bld.ToString(), "SQL Server CE")
' Empty the string so that it can be used again.
bld.Remove(0, bld.Length)
Next err
End Sub
As I said above: the code that I put here needs to be debugged...I have only extracted some parts from my project and put here. Hope this will help you!
I need your help please, I have a serious problem in my SQL request, it should show me the list of patients of the service Nephro but it shows me the list of all patients, so I think the SQL query does not work at all
This is the code :
Private Sub btnConnexion_Click()
Dim Categ As Integer
Dim Service As String
Dim IdProf As Integer
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
'vérification que l'utilisater a bien entrer e login et le mot de passe
Me.txtlogin.SetFocus
If IsNull(Me.txtlogin) Then
MsgBox "svp entrer votre login ", vbInformation, "login required "
Me.txtlogin.SetFocus
ElseIf IsNull(Me.txtmdp) Then
MsgBox "svp entrer votre mots de passe ", vbInformation, "mdp required "
Me.txtmdp.SetFocus
Else
'vérification que le login et le mdp sont corrects
If (IsNull(DLookup("login", "dbo_Authentification", "login='" & Me.txtlogin.Value & "'"))) Or _
(IsNull(DLookup("mdp", "dbo_Authentification", "mdp='" & Me.txtmdp.Value & "'"))) Then
MsgBox "login ou mdp incorrect"
Else
'récupération de l'IdCatégorie dans Categ, pour préciser les sessions des acteurs selon leurs catégories professionneles
Categ = DLookup("IdCategorie", "dbo_Professionnel", "IdProfessionnel = " & DLookup("IdCompte", "dbo_Authentification", "login='" & Me.txtlogin.Value & "'"))
'DoCmd.Close
If Categ = 3 Then
DoCmd.OpenForm "role"
Else
DoCmd.OpenForm "ListingPatients"
'Service récupère le service du professionnel authentifié pour l'afficher à l'entete du formulaire "ListingPatients"
Service = Nz(DLookup("IntituleServ", "dbo_Service", "IdService = " & DLookup("IdService", "dbo_Professionnel", "IdProfessionnel = " & DLookup("IdCompte", "dbo_Authentification", "login='" & Me.txtlogin.Value & "'"))), "inconnu")
Forms![ListingPatients]![txtIntituleServ] = Service
strSQL = "SELECT dbo_Patient.*, dbo_Service.IntituleServ, dbo_HospitalisatAcuelle.lit, dbo_Professionnel.IdProfessionnel, dbo_HospitalisatAcuelle.DateEntree, dbo_HospitalisatAcuelle.DateSortie FROM dbo_Service INNER JOIN ((dbo_Professionnel INNER JOIN dbo_Authentification ON dbo_Professionnel.IdProfessionnel = dbo_Authentification.IdCompte) INNER JOIN (dbo_Patient INNER JOIN (dbo_HospitalisatAcuelle INNER JOIN dbo_DonneePatientActuelles ON dbo_HospitalisatAcuelle.IdHosp = dbo_DonneePatientActuelles.IdHosp) ON dbo_Patient.IdPatient = dbo_DonneePatientActuelles.IdPatient) ON dbo_Professionnel.IdProfessionnel = dbo_HospitalisatAcuelle.IdProfessionnel) ON dbo_Service.IdService = dbo_Professionnel.Idservice WHERE (((dbo_HospitalisatAcuelle.DateEntree)<=Now()) AND ((dbo_HospitalisatAcuelle.DateSortie)>Now())) OR (((dbo_HospitalisatAcuelle.DateSortie) Is Null))"
strSQL = strSQL & " AND [dbo_Service]![IntituleServ] = ' " & Service & " ' "
Set rs = db.OpenRecordset(strSQL)
rs.Close
Set rs = Nothing
Set db = Nothing
End If
End If
End If
End Sub
Thank you very much
Check the WHERE clause of your VBA recordset SQL query. Your parenthesis set may be out of order. As you can see dbo_Service![IntituleServ] field is not contained but hangs out on an OR statement.
Consider moving the last parenthesis after the DateSortie >=Now() to after DateSortie Is Null.
WHERE
(
(
(dbo_HospitalisatAcuelle.DateEntree)<=Now()
) AND
(
(dbo_HospitalisatAcuelle.DateSortie)>Now()
)
)
OR
(
(
(dbo_HospitalisatAcuelle.DateSortie) Is Null
)
)
AND
[dbo_Service]![IntituleServ] = ' " & Service & " ' "
The DB object doesn't support queries, it can only be used to open entire tables.
Instead, use a QueryDef object. So the following code:
Set rs = db.OpenRecordset(strSQL)
should be
'up at the top
Dim qdf as QueryDef
'... code
Set qdf = db.CreateQueryDef("",strSQL)
set rs = qdf.OpenRecordSet(DbOpenSnapshot)
'... at the bottom
qdf.close
Also, there is a problem with your SQL the WHERE part should probably be
" WHERE (dbo_HospitalisatAcuelle.DateEntree<=Now() " & _
" AND (dbo_HospitalisatAcuelle.DateSortie>Now() OR dbo_HospitalisatAcuelle.DateSortie Is Null)) " & _
" AND [dbo_Service].[IntituleServ] = ' " & Service & " ' "
(note the placement of the brackets ())
I'm facing problem when i tried to delete data from database.I'm using Access Database
strqry3 = "SELECT * " & _
"FROM ((tbl_l0_est INNER JOIN tbl_project_resource_matrix ON
tbl_l0_est.pr_matrix_key = tbl_project_resource_matrix.pr_matrix_key) INNER JOIN
tbl_proj_app_impacted ON tbl_project_resource_matrix.project_key =
tbl_proj_app_impacted.project_key) " & _
"WHERE app_impacted = '" & Text & "'"
Set rst3 = CurrentDb.OpenRecordset(strqry3)
If rst3.EOF = True Then
'MsgBox ("")
Else
Do Until rst3.EOF
rst3.Delete
rst3.MoveNext
Loop
End If
Please Advise
The fact is that you cant delete records in that way (calling .delete method) from a composte SELECT. That is valid only in select * from onlyOneTable where some=condition
The same even occurs with other databases using for example ADO .delete method, which fails. The reason is that is no clear to the RDBM to which table .delete refers to.
I have an MS Access 2007 front end to a MS SQL Server 2008R2 back end.
I've got a query that's part of a loop, and it's suddenly started generating Run-time error '3146': ODBC--call failed. errors on one query as the loop itterates. Oddly, it's not the first iteration. EDIT: When I say suddenly, it's been running like this just fine for several months (probably since March).
Set db = CurrentDb
db.QueryTimeout = 480 'thought there was a timeout issue, so set this very high
Set SupvRS = db.OpenRecordset("SELECT DISTINCT tblProcessors.Supervisor, tblProcessors.SupervisorEmail " & _
" FROM tblProcessors INNER JOIN (tblAuditPr INNER JOIN tblAuditPr_A ON tblAuditPr.PrAudit_ID = tblAuditPr_A.PrAudit_ID)" & _
" ON tblProcessors.Processor = tblAuditPr_A.Processor" & _
" WHERE tblProcessors.Supervisor IS NOT NULL " & _
" AND tblAuditPr.EndDate BETWEEN " & GetSQLDate(Me.txtFrom) & " AND " & GetSQLDate(Me.txtTo) & _
" AND tblProcessors.Processor<>'Default Processor' " & _
" AND tblAuditPr_A.Answer Not In ('NA','NF')" & _
" AND tblAuditPr.Status = 'Submitted'")
Do While Not SupvRS.EOF
'Send Supervisor Email
Attachment = PARG.GenerateAuditReport(SupvRS.Fields("Supervisor"), parSupervisor, Me.txtFrom, Me.txtTo)
Set EmailRS = db.OpenRecordset("SELECT * FROM tblProcessors WHERE Supervisor = " & GetSQLString(SupvRS.Fields("Supervisor")))
If EmailRS.EOF Then
Err.Raise -234923, Description:="Cannot find tblProcessors record for " & SupvRS.Fields("Supervisor") & "."
End If
If IsNull(EmailRS.Fields("SupervisorEmail")) Then
MailTo = <redacted>
Else
MailTo = EmailRS.Fields("SupervisorEmail")
End If
Set EmailRS = Nothing
Mailer.AddMailDocument MailTo:=MailTo, _
Subject:=Subject, _
Body:=Body, _
Attachments:=Attachment, _
From:=<redacted>
'Iterate processor emails if requested.
If Me.chkProcessor Then
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'----------------------------------------------------------------------------------------
'ERROR occurs here, but only after several supervisors have successfully passed through
Set ProcRS = db.OpenRecordset("SELECT DISTINCT tblProcessors.Processor, tblProcessors.ProcessorEmail FROM tblAuditPr" & _
" INNER JOIN (tblProcessors INNER JOIN tblAuditPr_A ON tblProcessors.Processor = tblAuditPr_A.Processor) " & _
" ON tblAuditPr.PrAudit_ID = tblAuditPr_A.PrAudit_ID" & _
" WHERE tblProcessors.Supervisor = " & GetSQLString(SupvRS.Fields("Supervisor")) & _
" AND tblAuditPr.EndDate BETWEEN " & GetSQLDate(Me.txtFrom) & " AND " & GetSQLDate(Me.txtTo))
'----------------------------------------------------------------------------------------
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Do While Not ProcRS.EOF
If Not IsNull(ProcRS.Fields("ProcessorEmail")) Then
On Error Resume Next
Attachment = PARG.GenerateAuditReport(ProcRS.Fields("Processor"), parProcessor, Me.txtFrom, Me.txtTo)
If Attachment <> "" Then
MailTo = ProcRS.Fields("ProcessorEmail")
Mailer.AddMailDocument MailTo:=MailTo, _
Subject:=Subject, _
Body:=Body, _
Attachments:=Attachment, _
From:=<redacted>
Else
Err.Clear
End If
On Error GoTo 0
End If
ProcRS.MoveNext
Loop
Set ProcRS = Nothing
End If
SupvRS.MoveNext
Loop
As noted in the code, the error occurs on an inner loop that successfully executes for other supervisors. It does consistantly break on one particular individual. Using the GetSQLString and GetSQLDate functions (returns ' delimited, double '' when necessary, pretty strings, and # delimited dates, respectivly, for passing Access queries through to SQL Server) in break mode, I duplicated the exact query that was giving me problems in an Access query. It returned a timeout error, but changing the database default timeout (and closing/opening the db) didn't resolve the issue. I pasted the exact same query into SSMS (replacing the # date delimiters with ') and it executed just fine there (taking about 1:30-2:00 to execute each try).
Taking a pause in typing up this post, I put some error trapping in to see if I could get the actual error message SQL Server was returning, when it ran without error. To me, that indicates that it is likely a time out issue. Anyone have a more educated guess as to what it actually is, or a suggestion on how to make the query more efficient so it doesn't time out?