VB in Access 2000 : ado query got different result each time? - ms-access

I got a form, which has 2 buttons, 1 is to set the input data file, 1 is to start a sub, the sub should make a query against the db. But the same simple query "select * from opt_in_customer_record;" return different thing! That's horrible! Why???
Here is my code, btnBrowse_Click() will pop window for user to select file, everytime I will the same file. btnGenData_Click() is the sub which got problem.
for the data file, here is the first 20 lines, Event_Plan_Code is the first column.
5BUDP;HongKong;050111;520010100000800
5BUDP;HongKong;010111;520010100100867
5BUDP;HongKong;130111;520010100182001
3BUDP;HongKong;050111;520010100244746
5BUDP;HongKong;040111;520010100282676
1BUDP;HongKong;110111;520010100310573
1BUDP;HongKong;120111;520010100310573
3BUDP;HongKong;310111;520010100361924
1BUDP;HongKong;310111;520010100392644
1BUDP;HongKong;290111;520010100406914
3BUDP;HongKong;280111;520010100429143
3BUDP;HongKong;190111;520010100440403
3BUDP;HongKong;300111;520010100482444
1BUDP;HongKong;130111;520010100523409
3BUDP;HongKong;210111;520010100576847
5BUDP;HongKong;230111;520010100583232
3BUDP;HongKong;200111;520010100637103
3BUDP;HongKong;160111;520010100639083
3BUDP;HongKong;190111;520010100666157
3BUDP;HongKong;250111;520010100774408
I made the program to stop if the first character of Event_Plan_Code is 1, just to stop the program for debugging. And each time I press the button, different result I got:
1st run:
5BUDP
5BUDP
5BUDP
3BUDP
5BUDP
1BUDP
it make sense.
2nd run:
3BUDP
1BUDP
The problem is that the query should start over again and the result should be the same! Now different result I got.
Thank you very much if you may answer my question!
Option Compare Database
Private Sub btnBrowse_Click()
Dim filePath As String
filePath = LaunchCD(Me)
txtFilePath.Value = filePath
txtStatus.Value = ""
End Sub
Private Sub btnGenData_Click()
'On Error GoTo Error_Handling
Dim extractCdrFlag As Boolean
txtStatus.Value = ""
If IsNull(txtFilePath.Value) Then
MsgBox "Please enter a valid input file location."
Else
txtStatus.Value = ""
txtStatus.Value = txtStatus.Value & "Deleting previous record from table Opt_In_Customer_Record..." & vbCrLf
CurrentDb.Execute "deleteAll"
txtStatus.Value = txtStatus.Value & "Delete successfully." & vbCrLf
If FileExists(txtFilePath.Value) Then
txtStatus.Value = txtStatus.Value & "Trying to import data from file..." & vbCrLf
DoCmd.TransferText acImportDelim, "Import_Specification", "Opt_In_Customer_Record", txtFilePath.Value, False
txtStatus.Value = txtStatus.Value & "Data imported successfully." & vbCrLf
Testing
txtStatus.Value = ""
Else
MsgBox "File does not exist. Please enter again."
End If
End If
Exit Sub
Error_Handling:
MsgBox "Error while generating data! Please check your data setting!"
Exit Sub
End Sub
Sub Testing()
'On Error GoTo Error_Handling
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
Dim eventPlanCode As String
Dim visitedCountry As String
Dim startDateTxt As String
Dim startDate As Date
Dim endDate As Date
Dim imsi As String
Dim currentMonth As String
Dim nextMonth As String
Dim currentYear As String
Dim nextYear As String
Dim temp As Integer
Dim sql As String
'MsgBox CurrentDb.Name
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = CurrentDb.Name
.Open
End With
'MsgBox conConnection.ConnectionString
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
'Debug.Print txtStatus.Value
eventPlanCode = rstRecordSet!Event_Plan_Code
visitedCountry = rstRecordSet!Visited_Country
startDateTxt = rstRecordSet!Start_Date
imsi = rstRecordSet!imsi
currentMonth = Mid$(startDateTxt, 3, 2) '01
currentYear = "20" & Mid$(startDateTxt, 5, 2) '2011
startDate = DateSerial(Val(currentYear), Val(currentMonth), Val(Mid$(startDateTxt, 1, 2)))
endDate = startDate + Val(Mid$(eventPlanCode, 1, 1))
MsgBox rstRecordSet!Event_Plan_Code
If (Mid$(eventPlanCode, 1, 1) = "1") Then
Exit Sub
End If
'MsgBox startDate & " " & endDate
If (currentMonth = "01") Then
nextMonth = "02"
ElseIf (currentMonth = "02") Then
nextMonth = "03"
ElseIf (currentMonth = "03") Then
nextMonth = "04"
ElseIf (currentMonth = "04") Then
nextMonth = "05"
ElseIf (currentMonth = "05") Then
nextMonth = "06"
ElseIf (currentMonth = "06") Then
nextMonth = "07"
ElseIf (currentMonth = "07") Then
nextMonth = "08"
ElseIf (currentMonth = "08") Then
nextMonth = "09"
ElseIf (currentMonth = "09") Then
nextMonth = "10"
ElseIf (currentMonth = "10") Then
nextMonth = "11"
ElseIf (currentMonth = "11") Then
nextMonth = "12"
ElseIf (currentMonth = "12") Then
nextMonth = "01"
End If
temp = Val(currentYear)
temp = temp + 1
nextYear = Str(temp)
'MsgBox currentYear & currentMonth & " " & nextYear & nextMonth
'Exit Do
rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True
End If
'sql = "select * from ( select * from " & "dbo.inbound_rated_all_" & currentYear & currentMonth & " A inner join Opt_In_Customer_Record B "
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Sub
Error_Handling:
MsgBox "Error during function Testing!"
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Sub
End Sub

If you want the rows in a particular order, add an ORDER BY clause to your query:
select * from opt_in_customer_record order by event_plan_code
Actually, event_plan_code isn't the right column because it contains duplicates, but that should point you in the right direction.

Related

VBA code does not work in some versions of Office, works in others

Number of query values and destination fields are not the same.
Debug redirects me to this line: dbs.Execute strSQL, dbFailOnError
Here is my code:
Public Function GetMatches(Column1 As String, Column2 As String)
Dim dbs As DAO.Database
Dim rcrdStColumn1 As Recordset
Dim rcrdStColumn2 As Recordset
Dim defaultTable1 As String
Dim defaultTable2 As String
Dim strSQL As String
Dim strSQLColumn1 As String
Dim strSQLColumn2 As String
Dim firstCurrentValue As String
Dim secondCurrentValue As String
Dim currentResultComparison As Double
Dim maxResultComparison As Double
Dim checkColumn1 As Boolean
Dim checkColumn2 As Boolean
Set dbs = CurrentDb
defaultTable1 = "CEE_Names_for_CUST_DES"
defaultTable2 = "GSNDG_Names"
'Check if column exists in table 1
checkColumn1 = checkColumn(Column1, defaultTable1)
checkColumn2 = checkColumn(Column2, defaultTable2)
If checkColumn1 = False Then
MsgBox ("Column 1 does not exist")
ElseIf checkColumn2 = False Then
MsgBox ("Column 2 does not exist")
Else
strSQLColumn1 = "SELECT " & Column1 & " FROM " & defaultTable1 & " ;"
Set rcrdStColumn1 = dbs.OpenRecordset(strSQLColumn1)
strSQLColumn2 = "SELECT " & Column2 & " FROM " & defaultTable2 & " ;"
Do While Not rcrdStColumn1.EOF
firstCurrentValue = rcrdStColumn1.Fields(Column1)
maxResultComparison = 0
Set rcrdStColumn2 = dbs.OpenRecordset(strSQLColumn2)
Do While Not rcrdStColumn2.EOF
secondCurrentValue = rcrdStColumn2.Fields(Column2)
currentResultComparison = modSimil.Simil(firstCurrentValue, secondCurrentValue)
strSQL = "INSERT INTO results(Column1, Column2, Similarities)" _
& " VALUES( '" & clearString(firstCurrentValue) & "', '" & clearString(secondCurrentValue) & "', " & Round(currentResultComparison, 2) & " )"
dbs.Execute strSQL, dbFailOnError
If currentResultComparison > maxResultComparison Then
maxResultComparison = currentResultComparison
End If
rcrdStColumn2.MoveNext
Loop
rcrdStColumn1.MoveNext
Loop
End If
dbs.Close
Set dbs = Nothing
End Function
Function checkColumn(strColumn As String, strTable As String) As Boolean
On Error GoTo checkColumnError
If (DCount(strColumn, strTable) = 0) Then
checkColumn = False
Else
checkColumn = True
End If
checkColumnError:
If Err.Number = 2741 Then
MsgBox ("2741")
ElseIf checkColumn Then
checkColumn = True
Else
checkColumn = False
End If
End Function
Function clearResult()
Dim dbs As DAO.Database
Dim strSQL As String
Set dbs = CurrentDb
strSQL = "DELETE FROM results"
dbs.Execute strSQL, dbFailOnError
dbs.Close
Set dbs = Nothing
End Function
Function clearString(str As String) As String
clearString = Replace(str, "'", "")
End Function

Access error: can not add records joint key of table 'TableName' not in recordset

I have two linked Tables 'tblPatients' and 'tblDSA' and two continues forms 'frmPatients' and 'frmDSA'. When I create a new patient via 'frmPatient'I would like to add a new record for that patient in 'frmDSA' without closing the form.
On 'frmPatients' next to each record there is a button 'SaveNewRecord' that does the following:
(1)saves a new record to 'tblPatients' and also filters
(2) opens 'frmDSA' to display related records to that Patients.
Here is the filtering code:
If Not Me.NewRecord Then
DoCmd.OpenForm "DSAfrm", _
WhereCondition:="LABCODE=" & Me.LABCODE
End If
Here is what happens:
After the 'DSAfrm' pops up and I try to enter a new record I get the following error."can not add records joint key of table 'TableName' not in record-set"
The new patient has been save to 'tblPatients' but Access is not letting me add any new records. Please help!
Here is the code that I use to save the new records:
Private Sub Command385_Click()
Dim db As DAO.Database
Dim PatientTable As DAO.Recordset
Dim DSAtable As DAO.Recordset2
Dim errMsg As String 'Where we will store error messages
Dim errData As Boolean 'Default = False if we have an error we will set it to True.
Dim i As Integer 'used as a counter in For..Next loops.
Dim x As Integer 'used as counter in For..Next loops.
Dim errorArray(0 To 3) As String 'Array to hold the error messages so we can 'use them if needed.
If Me.LABCODE.Value = "" Then
errorArray(0) = "Must Enter Labcode."
errData = True
End If
If Me.LastName.Value = 0 Then
errorArray(1) = "Must Enter Patient Number"
errData = True
End If
If Me.FirstName.Value = "" Then
errorArray(2) = "Must Enter Insurance Type"
errData = True
End If
If Me.MRN.Value = "" Then
errorArray(3) = "Must Enter Intake Nurse"
errData = True
End If
'MsgBox "errData = " & errData
If errData = True Then
i = 0
x = 0
For i = 0 To 3
If errorArray(i) <> "" Then
If x > 0 Then
errMsg = errMsg & vbNewLine & errorArray(i)
Else
errMsg = errorArray(i)
x = x + 1
End If
End If
Next i
MsgBox errMsg & vbNewLine & "Please try again."
errMsg = ""
Me.LABCODE.SetFocus
Exit Sub
End If
Set db = CurrentDb()
Set PatientTable = db.OpenRecordset("tblPatients")
With PatientTable
.AddNew
!LABCODE = Me.LABCODE.Value
!LastName = Me.LastName.Value
!FirstName = Me.FirstName.Value
!MRN = Me.MRN.Value
!MRNTwo = Me.MRN2.Value
Debug.Print Me.MRN.Value
'!CPI#2 = Me.MRN2.Value
!Kidney = Me.cbKidney.Value
!Heart = Me.cbHeart.Value
!Lung = Me.cbLung.Value
!Liver = Me.cbLiver.Value
!Pancreas = Me.cbPancreas.Value
!DateLogged = Format(Date, "MM/DD/YY")
.Update
End With
'End If
Set DSAtable = db.OpenRecordset("tblDSA")
With DSAtable
.AddNew
!LABCODE = Me.LABCODE.Value
.Update
End With
'Let the user know it worked.
MsgBox "This patient has been added successfully.", vbOKOnly
'If Not Me.NewRecord Then
DoCmd.OpenForm "DSAfrm", _
WhereCondition:="LABCODE=" & Me.LABCODE
'End If
End Sub

ADODB Recordset Open returns Error#:13

I've been using stackoverflow for over a year now but this is my first post so if I do something wrong, please let me know and I'll try to do better next time.
I'm currently using MS Access 2003 as a front-end data entry application with an MS SQL 2008 back end. A function used by just about every form in the app is breaking for no reason that I can determine when called from a specific subroutine.
Calling subroutine:
Private Sub Form_Load()
strRep = GetAppCtl("ConUID")
FLCnnStr = GetAppCtl("ConStrApp")
strSQL2 = "SELECT EMPNMBR, First, Last, TSLogin, IsITAdmin, " & _
" IsManager, Pwd, AppAuthLvl, SEX, AppTimeOutMins " & _
" FROM utEmplList WHERE EMPNMBR = " & _
strRep & ";"
Set cnn = New ADODB.Connection
With cnn
.ConnectionString = FLCnnStr
.Open
End With
Set rst = New ADODB.Recordset
rst.Open strSQL2, cnn, adOpenDynamic, adLockReadOnly
intAppAuthLvl = rst!AppAuthLvl
' Loaded/opened with parameters / arguments (OpenArgs)?
If Not IsNull(Me.OpenArgs) And Me.OpenArgs <> "" Then
Me.txtEmpSecLvl = Me.OpenArgs
Else
Me.txtEmpSecLvl = "99999<PROGRAMMER>Login:-1,-1\PWD/999|M!60$"
End If
Me.lblDateTime.Caption = Format(Now, "dddd, mmm d yyyy hh:mm AMPM")
If FirstTime <> "N" Then
' Set default SQL select statement with dummy WHERE clause
' (DealID will always be <> 0!)
strDate = DateAdd("d", -14, Now())
strSQLdefault1 = "SELECT *, DealHasTags([PHONE10],[REP]) as DealHasTags FROM utDealSheet WHERE DealID <> 0 AND (STATUS BETWEEN '00' AND '99') "
strSQLdefault2 = "SELECT *, DealHasTags([PHONE10],[REP]) as DealHasTags FROM utDealSheet WHERE DATE >= #" & strDate & "# AND DealID <> 0 AND (STATUS BETWEEN '00' AND '99') "
Me.LoggingDetail.Enabled = False
Me.LoggingDetail.Visible = False
If rst!AppAuthLvl <= 200 Then
strSQL = strSQLdefault1 & ";"
Me.LoggingDetail.Form.RecordSource = strSQL
Else
strSQL = strSQLdefault2 & ";"
Me.LoggingDetail.Form.RecordSource = strSQL
End If
FirstTime = "N"
End If
DoCmd.Maximize
End Sub
Function that is breaking:
Public Function GetAppCtl(strFldDta As String) As Variant
Dim strSQL As String
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim strConnString As String
If IsNull(strFldDta) Then GetAppCtl = "ERR"
' Starting string
strConnString = "ODBC;Description=SQLUmgAgr;DRIVER=SQL Server;SERVER="
' Set a connection object to the current Db (project)
Set cnn = CurrentProject.Connection
strSQL = "Select ConStrApp, ConStrTS, DftOfficeID, RecID, VerRelBld, SeqPrefix, ConDb, ConDbTs, ConUID, ConUIDTS, ConPWD, ConPWDTs, ConServer, ConServerTS, ConWSID, ConWSIDTS from tblAppCtl WHERE RecID = 1;"
Set rst = New ADODB.Recordset
rst.Open strSQL, cnn, adOpenKeyset, adLockReadOnly
' If a Db error, return 0
If Err.Number <> 0 Then
GetAppCtl = ""
GoTo CleanUp
End If
' If no record found, return 0
If rst.EOF Then
GetAppCtl = ""
Else ' Otherwise, return Version/Build
Select Case strFldDta
Case Is = "ConStrApp" ' connection string - application
strConnString = strConnString & Trim(rst!Conserver) & ";" _
& "UID=" & Trim(rst!ConUID) & ";PWD=" & Trim(rst!conpwd) & ";" _
& "DATABASE=" & Trim(rst!ConDb) & ";WSID=" & Trim(rst!ConWSID)
GetAppCtl = strConnString
Case Is = "ConStrTS" ' connection string - TouchStar
strConnString = strConnString & Trim(rst!ConserverTS) & ";" _
& "UID=" & Trim(rst!ConUIDTS) & ";PWD=" & Trim(rst!conpwdTS) & ";" _
& "DATABASE=" & Trim(rst!ConDbTS) & ";WSID=" & Trim(rst!ConWSID)
GetAppCtl = strConnString
Case Is = "DftOfficeID" ' Default AGR office ID
GetAppCtl = rst!DftOfficeID
Case Is = "VerRelBld" ' Current APP ver/rel/bld (to be checked against SQL Db
GetAppCtl = rst!VerRelBld
Case Is = "SeqPreFix" ' Sales seq# prefix (ID as per office for backward capability)
GetAppCtl = rst!SeqPrefix
Case Is = "ConUID"
GetAppCtl = rst!ConUID
End Select
End If
CleanUp:
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Function
The function is breaking here, but only when called by the above sub:
Set rst = New ADODB.Recordset
rst.Open strSQL, cnn, adOpenKeyset, adLockReadOnly
' If a Db error, return 0
If Err.Number <> 0 Then
GetAppCtl = ""
GoTo CleanUp
End If
When called from any other sub it works fine and returns the appropriate value. Please help.
I don't have an actual explanation as to why it was returning an error code but by removing the error checking the process worked. If anyone has an actual explanation as to what was actually causing the issue it would be greatly appreciated.
I know this post's a bit old and OP might have solved the problem.
I encountered the same problem and solved it by changing "Microsoft ActiveX Data Objects 2.5 Library" to "Microsoft ActiveX Data Objects 2.8 Library" from VBA Tools => References.

More efficinet way to filter form

I have the following code:
Public Function BuildSQL(stQueryName As String, stWhereClause As String) As String
On Error GoTo Err_BuildSQL
Dim SQLcmd As String
Dim intPos As Integer
Dim db As Database
Dim qryOrig As QueryDef
Set db = CurrentDb()
Set qryOrig = db.QueryDefs(stQueryName)
SQLcmd = qryOrig.SQL
intPos = InStr(SQLcmd, "WHERE")
If intPos > 0 Then
SQLcmd = Left(SQLcmd, intPos - 1)
End If
intPos = InStr(SQLcmd, ";")
If intPos > 0 Then
SQLcmd = Left(SQLcmd, intPos - 1)
End If
If Not (stWhereClause = "") Then
SQLcmd = Trim(SQLcmd) & " WHERE " & stWhereClause & ";"
Else
SQLcmd = Trim(SQLcmd) & ";"
End If
BuildSQL = SQLcmd
Exit_BuildSQL:
Set qryOrig = Nothing
Set db = Nothing
Exit Function
Err_BuildSQL:
MsgBox Err.Description
Resume Exit_BuildSQL
End Function
Private Sub SandBox_Click()
On Error GoTo Err_SandBox_Click
Dim db As Database
Dim rs As Recordset
Dim stSQL As String
Dim stFrmName As String
Dim stQryName As String
Dim stSQLWhere As String
Dim stIDList As String
stFrmName = "Libri"
stQryName = "Libri_All_Query"
'Define WHERE clause
stSQLWhere = ""
If Not (IsNull([Forms]![Libreria]![Editore]) Or [Forms]![Libreria]![Editore] = "") Then
stSQLWhere = stSQLWhere & "Libri_Editori.Editore = '" & [Forms]![Libreria]![Editore] & "'"
End If
If Not (IsNull([Forms]![Libreria]![CognomeAutore]) Or [Forms]![Libreria]![CognomeAutore] = "") Then
If (stSQLWhere = "") Then
stSQLWhere = stSQLWhere & "Autori.Cognome = '" & [Forms]![Libreria]![CognomeAutore] & "'"
Else
stSQLWhere = stSQLWhere & " AND Autori.Cognome = '" & [Forms]![Libreria]![CognomeAutore] & "'"
End If
End If
'Here several more fields of the search form will be checked and added
stSQL = BuildSQL(stQryName, stSQLWhere)
'*** Code in question!
Set db = CurrentDb()
Set rs = db.OpenRecordset(stSQL)
If Not (rs.EOF And rs.BOF) Then
stIDList = "("
rs.MoveFirst
Do Until rs.EOF = True
If (stIDList = "(") Then
stIDList = stIDList & rs.Fields(0)
Else
stIDList = stIDList & ", " & rs.Fields(0)
End If
rs.MoveNext
Loop
stIDList = stIDList & ")"
Else
Err.Description = "Errore! Recordset vuoto."
Resume Err_SandBox_Click
End If
DoCmd.OpenForm stFrmName, , , , acFormReadOnly
Access.Forms(stFrmName).RecordSource = "SELECT * FROM Libri WHERE Libri.ID IN " & stIDList
'**** End code in question
Exit_SandBox_Click:
Set db = Nothing
Set rs = Nothing
Exit Sub
Err_SandBox_Click:
MsgBox Err.Description
Resume Exit_SandBox_Click
End Sub
This code works as I want but "looks" slow even with a test DB with only a few records in each table.
I believe the time is spent (how can I check if this is true?) in the loop between comments.
Is there a more basic, obvious and efficient way to filter the form than creating a recordset and looping through it as I am doing?
The form "Libri" is a big one with several subform to be able to see all the data of a Book.
The query "Libri_All_Query" is a join of almost all tables in the DB and the code shown is executed from a form where I plan to add all possible search fields.
Forms have a filter property:
stWhereClause = "Title Like '" & Me.txtSearch & "*'"
Me.Filter = stWhereClause
Me.FilterOn = True
The filter should be constructed in a similar way to a WHERE statement. There are some limitations compared with Where. You may wish to check with DCount that records will be returned.
EDIT
If you want a set of records where a subform contains only certain records, you need something on these lines:
SELECT b.Title
FROM Books b
WHERE b.ID IN (
SELECT j.BookID FROM BooksAuthorJunction j
INNER JOIN Authors a ON j.AuthorID = a.ID
WHERE a.Author Like "Arn*")
There are advantages in building more that one form, books as a main form and authors as a subform, then authors as a main form and books as a subform. It is often easier on the user.

[VBA]Error while making ADO query in MS Access with linked table

Error #-2147467259
ODBC--call failed.
(Source: Microsoft JET Database Engine)
(SQL State: 3146)
(NativeError: -532940753)
No Help file available
What happened? What is the reason of this? I can make a query to a different sql server via odbc linked table(uat env), but when I go to prod server, this error come out.
I am using ms access 2000, and built a form within it, then make a query to the server when a button was pressed. The prod server get A LOT of records, while the uat server only have 3000 records, however I don't think that is a problem...
Thank to any possible help!!
This is the part of the queries:
Sub extractInboundCdr()
On Error GoTo Error_Handling
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
Dim Err As ADODB.Error
Dim strError As String
Dim eventPlanCode As String
Dim visitedCountry As String
Dim startDateTxt As String
Dim startDate As Date
Dim endDate As Date
Dim imsi As String
Dim currentMonth As String
Dim nextMonth As String
Dim currentYear As String
Dim nextYear As String
Dim temp As Integer
Dim i As Integer
Dim j As Integer
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = CurrentDb.Name
.Open
End With
conConnection.CommandTimeout = 0
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
eventPlanCode = rstRecordSet!Event_Plan_Code
visitedCountry = rstRecordSet!Visited_Country
startDateTxt = rstRecordSet!start_date
imsi = rstRecordSet!imsi
currentMonth = Mid$(startDateTxt, 1, 3)
currentYear = Mid$(startDateTxt, 8, 4)
nextMonth = ""
If (currentMonth = "Jan") Then
currentMonth = "01"
nextMonth = "02"
ElseIf (currentMonth = "Feb") Then
currentMonth = "02"
nextMonth = "03"
ElseIf (currentMonth = "Mar") Then
currentMonth = "03"
nextMonth = "04"
ElseIf (currentMonth = "Apr") Then
currentMonth = "04"
nextMonth = "05"
ElseIf (currentMonth = "May") Then
currentMonth = "05"
nextMonth = "06"
ElseIf (currentMonth = "Jun") Then
currentMonth = "06"
nextMonth = "07"
ElseIf (currentMonth = "Jul") Then
currentMonth = "07"
nextMonth = "08"
ElseIf (currentMonth = "Aug") Then
currentMonth = "08"
nextMonth = "09"
ElseIf (currentMonth = "Sep") Then
currentMonth = "09"
nextMonth = "10"
ElseIf (currentMonth = "Oct") Then
currentMonth = "10"
nextMonth = "11"
ElseIf (currentMonth = "Nov") Then
currentMonth = "11"
nextMonth = "12"
ElseIf (currentMonth = "Dec") Then
currentMonth = "12"
nextMonth = "01"
Else
GoTo Error_Handling
End If
temp = Val(currentYear)
temp = temp + 1
nextYear = CStr(temp)
Exit Do
Loop Until rstRecordSet.EOF = True
End If
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Set connConnection = Nothing
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = CurrentDb.Name
.Open
End With
conConnection.CommandTimeout = 0
Dim thisMonthTable As String
Dim nextMonthTable As String
thisMonthTable = "dbo_inbound_rated_all_" & currentYear & currentMonth
If (currentMonth = "12") Then
nextMonthTable = "dbo_inbound_rated_all_" & nextYear & nextMonth
Else
nextMonthTable = "dbo_inbound_rated_all_" & currentYear & nextMonth
End If
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "(SELECT A.IMSI_NUMBER, A.CALL_DATE, A.CALL_TIME, A.VOL_KBYTE, A.TOTAL_CHARGE ,datevalue(A.call_date), A.Service_Code As theDate FROM " & thisMonthTable & " AS A INNER JOIN Opt_In_Customer_Record AS B on A.imsi_number = B.imsi where A.Service_Code = 'GPRS' and Datevalue(A.call_date) >= Datevalue(B.start_date) And Datevalue(A.call_date) < (Datevalue(B.start_date) + val(LEFT(B.event_plan_code, 1))) ) " & _
"UNION " & _
"(SELECT A.IMSI_NUMBER, A.CALL_DATE, A.CALL_TIME, A.VOL_KBYTE, A.TOTAL_CHARGE ,datevalue(A.call_date), A.Service_Code As theDate FROM " & nextMonthTable & " AS A INNER JOIN Opt_In_Customer_Record AS B on A.imsi_number = B.imsi where A.Service_Code = 'GPRS' and Datevalue(A.call_date) >= Datevalue(B.start_date) And Datevalue(A.call_date) < (Datevalue(B.start_date) + val(LEFT(B.event_plan_code, 1))) ) " & _
"Order by A.IMSI_NUMBER, theDate"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockReadOnly
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
Dim sql As String
sql = "insert into IB_CDR values ("
For j = 0 To rstRecordSet.Fields.Count - 3 '''''Last 2 fields is not inserted
If (j = 3 Or j = 4) Then '''''These fields are number
sql = sql & rstRecordSet.Fields(j) & ","
Else
sql = sql & "'" & rstRecordSet.Fields(j) & "',"
End If
Next
sql = Left(sql, Len(sql) - 1) '''''Remove the last ','
sql = sql & ");"
CurrentDb.Execute sql
rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True
End If
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Sub
Error_Handling:
For Each Err In conConnection.Errors
strError = "Error #" & Err.Number & vbCr & _
" " & Err.Description & vbCr & _
" (Source: " & Err.Source & ")" & vbCr & _
" (SQL State: " & Err.SQLState & ")" & vbCr & _
" (NativeError: " & Err.NativeError & ")" & vbCr
If Err.HelpFile = "" Then
strError = strError & " No Help file available"
Else
strError = strError & _
" (HelpFile: " & Err.HelpFile & ")" & vbCr & _
" (HelpContext: " & Err.HelpContext & ")" & _
vbCr & vbCr
End If
Debug.Print strError
Next
Resume Next
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Sub
End Sub
The most common cause of this error is incorrect permissions on the folder containing the Access database. You will need to set write permissions.