This is my complete code. I was able to run the code once and get the record sets export to excel, but I can't do a different operation the second time.
It looks like after the record set is closed once, its not opening again. When I search second time it giving me the above error 3704.
Basically I have a form with three text boxes to search the database and then export the record sets to excel.
I might be missing something simple as I am not an experienced programmer.
Option Compare Database
Private Sub search_Click()
Dim cn As Object
Dim rs As ADODB.Recordset
Dim strSql As String
Dim strConnection As String
Dim xlApp As Object
Dim xlWb As Object
Dim xlWs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = New ADODB.Recordset
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\e3017764\Desktop\Master.accdb"
cn.Open strConnection
If (skill.Value = "" And location.Value = "" And project.Value = "") Then
MsgBox "Please Enter Atleast one criteria"
ElseIf (skill.Value <> "" And location.Value = "" And project.Value = "") Then
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE [Primary Skills] = '" & skill.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
ElseIf (skill.Value = "" And location.Value = "" And project.Value <> "") Then
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE Project = '" & project.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
ElseIf (skill.Value = "" And location.Value <> "" And project.Value = "") Then
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE Location = '" & location.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
ElseIf (skill.Value <> "" And project.Value <> "" And location.Value = "") Then
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE [Primary Skills] = '" & skill.Value & "' AND Project = '" & project.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
ElseIf (skill.Value <> "" And project.Value = "" And location.Value <> "") Then
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE [Primary Skills] = '" & skill.Value & "' AND Location = '" & location.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
ElseIf (skill.Value = "" And project.Value <> "" And location.Value <> "") Then
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE Project = '" & project.Value & "' AND Location = '" & location.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
ElseIf (skill.Value <> "" And project.Value <> "" And location.Value <> "") Then
rs.Open
strSql = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE [Primary Skills] = '" & skill.Value & "' AND Project = '" & project.Value & "' AND Location = '" & location.Value & "'"
rs.Open strSql, CurrentProject.Connection, adOpenStatic, adLockOptimistic
End If
MsgBox " Total Records Matched " & rs.RecordCount
Set xlApp = CreateObject("Excel.Application")
Set xlWb = xlApp.Workbooks.Add
Set xlWs = xlWb.Worksheets("Sheet1")
xlApp.Visible = True
xlApp.UserControl = True
xlWs.Cells(1, 1).Value = "E Code"
xlWs.Cells(1, 2).Value = "Name"
xlWs.Cells(1, 3).Value = "Project"
xlWs.Cells(1, 4).Value = "Location"
xlWs.Cells(2, 1).CopyFromRecordset rs
xlApp.Selection.CurrentRegion.Columns.AutoFit
xlApp.Selection.CurrentRegion.Rows.AutoFit
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
I agree with #Sobigen that none of your IFs are true the second time around. Maybe. Anyway, I think if you simplify the IFs, you might see the answer more quickly. Here's a rewrite to consider
Private Sub search_Click()
Dim rs As ADODB.Recordset
Dim sSql As String
Dim aWhere() As String
Dim lWhereCnt As Long
Dim xlApp As Object
Dim xlWs As Object
'This never changes, so make it a constant
Const sSELECT As String = "SELECT [Ecode/LC Code],[Resource Name],Project,Location FROM [Resource Details] WHERE "
'put each piece of your where clause in an array
If Len(Me.skill.Value) > 0 Then
lWhereCnt = lWhereCnt + 1
ReDim Preserve aWhere(1 To lWhereCnt)
aWhere(lWhereCnt) = "[Primary Skills] = '" & Me.skill.Value & "'"
End If
If Len(Me.location.Value) > 0 Then
lWhereCnt = lWhereCnt + 1
ReDim Preserve aWhere(1 To lWhereCnt)
aWhere(lWhereCnt) = "[Location] = '" & Me.location.Value & "'"
End If
If Len(Me.project.Value) > 0 Then
lWhereCnt = lWhereCnt + 1
ReDim Preserve aWhere(1 To lWhereCnt)
aWhere(lWhereCnt) = "[Project] = '" & Me.project.Value & "'"
End If
'If there's at least one criterion
If lWhereCnt > 0 Then
'build the sql and execute it
sSql = sSELECT & Join(aWhere, " And ") & ";"
Set rs = CurrentProject.Connection.Execute(sSql)
'if at least one record is returned put it in excel
If Not rs.BOF And Not rs.EOF Then
Set xlApp = CreateObject("Excel.Application")
Set xlWs = xlApp.Workbooks.Add.worksheets(1)
xlApp.Visible = True
xlApp.UserControl = True
xlWs.Cells(1, 1).Resize(1, 4).Value = Split("E Code,Name,Project,Location", ",")
xlWs.Cells(2, 1).CopyFromRecordset rs
xlApp.Selection.CurrentRegion.Columns.AutoFit
xlApp.Selection.CurrentRegion.Rows.AutoFit
rs.Close
Set rs = Nothing
Else
'if no records are return, take a look at the sql statement to see why
MsgBox sSql
End If
Else
MsgBox "Please Enter Atleast one criteria"
End If
End Sub
Related
Private Sub Form_Close()
Dim sSQL, stringSQL As String
Dim rst As DAO.Recordset
sSQL = "SELECT BarCode, [Goods Name] FROM tblInventory WHERE BarCode='" & Me.ID & "'"
Set rst = CurrentDb.OpenRecordset(sSQL)
If rst.EOF Then
stringSQL = "INSERT INTO tblInventory(BarCode,[Goods Name],Unit,[Unit Price],[Initial Stock],[Current Stock],[Exit Item]) values('" & Me.ID & "','" & Me.Description & "','" & Me.Unit & "'," & Replace(Format(Me.Price, "0.00"), ",", ".") & "," & Me.Amount & "," & Me.Amount & ",0)"
DoCmd.SetWarnings False
DoCmd.RunSQL (stringSQL) /this is where it is erroring out/
DoCmd.SetWarnings True
Else
stringSQL = "UPDATE tblInventory SET [Current Stock]=[Current Stock]+" & Me.Amount & " WHERE BarCode='" & Me.ID & "'"
DoCmd.SetWarnings False
DoCmd.RunSQL (stringSQL)
DoCmd.SetWarnings True
End If
rst.Close
End Sub
Private Sub ID_AfterUpdate()
Dim sSQL As String
Dim rst As DAO.Recordset
sSQL = "SELECT BarCode, [Goods Name], Unit, [Unit Price] FROM tblInventory WHERE BarCode='" & Me.ID & "'"
Set rst = CurrentDb.OpenRecordset(sSQL)
If rst.EOF Then
MsgBox "New Parts"
Me.Description.SetFocus
Else
Me.Description = rst(1).Value
Me.Unit = rst(2).Value
Me.Price = rst(3).Value
Me.Amount.SetFocus
End If
rst.Close
End Sub
The above errors out where indicated above when i run the insert to table it has error on the doCmd.RunSql (StringSQL) so not sure what i am doing wrong
I am having and issue using update batch. I have a loop that goes through a recordset updating values. I have a minimum of 333 things in the batch. When it gets to the 254th item it bails. is there a limit to a batch.
On Error GoTo Err_cmdProcessAll
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTableName As String
Dim strSql As String
'
Set cn = New ADODB.Connection
cn.Open "Provider=sqloledb; " & _
"Data Source=" & "BLD-FS-SQLVS04\PRDINST4" & ";" & _
"Initial Catalog=" & "HNFS_NetProv" & ";" & _
"Integrated Security=SSPI;"
cn.CursorLocation = adUseServer
Dim strSortField As String
Dim additionalwhere As String
If cboValue = "pc3Claims" Then
strTableName = "Seq3_PendedClaims_Ranked"
strSortField = "DaysSinceReceivedClaim"
' additionalwhere = " AND (member_eligibility_ud Not Like '%Program%')
strSql = "Select * " & _
"FROM " & strTableName & _
" WHERE (Complete Is Null) And (AssignedTo Is Null)" & additionalwhere & _
" ORDER BY cast( " & strSortField & " as int )" & strSort
ElseIf cboValue = "pc3ContractAssignments" Then
strSortField = "date"
additionalwhere = ""
strSql = "Select * " & _
"FROM " & strTableName & _
" WHERE (Complete Is Null) And (AssignedTo Is Null)" & additionalwhere & _
" ORDER BY CONVERT(varchar(10), CONVERT(datetime, [" & strSortField & "], 111), 121) " & strSort
End If
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = strSql
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
'make change to above to include
Dim i As Long
Dim j As Long
Dim strAssignAssociate As String
Dim lngAllocAmt As Long
For i = 1 To ListView6.ListItems.Count
If ListView6.ListItems(i).Checked Then
strAssignAssociate = ListView6.ListItems(i).SubItems(1)
Debug.Print strAssignAssociate
lngAllocAmt = ListView6.ListItems(i).Text
For j = 1 To lngAllocAmt
Debug.Print rs.Fields("AssignedTo")
rs.Fields("AssignedTo") = strAssignAssociate
Debug.Print rs.Fields("AssignedTo")
rs.MoveNext
Next j
End If
Next i
rs.UpdateBatch
MsgBox "All Finished", vbOKOnly, "Inventory Control"
Set rs = Nothing
Set cn = Nothing
I found the problem. I am using a non-keyed file. I found that I had duplicates in the file. this has been rectified and the above code works fine.
I am working on an Access DB that sorts and tracks my firm's business contacts. We have a form called "Contact Profile" whereby the user can select a given contact and view all of his information: First Name, Last Name, Company, Title, Email Address, etc.
On the profile, the user can update a contact's information with the "Update Info" button.
Every single field updates just fine--with the exception of Email Address. For example, I can change Joseph Smith, Programmer at Google to Joe Smith, Program Manager at GOOG with no issues.
But if I try to change joesmith#google.com to jsmith#google.com, the change does not save. Code is posted below. Could someone please take a look and let me know if they have any suggestions? Thanks!
Private Sub Command61_Click()
Dim strFirstName As String
Dim strLastName As String
Dim strIndustry As String
Dim strCountry As String
Dim strState As String
Dim strCity As String
Dim strCompany As String
Dim strTitle As String
Dim strStatus As String
Dim strPhone As String
Dim strEmail As String
Dim strOwner As String
Dim DateNow As String
'Allow user to leave some fields blank. User must fill in certain fields.
Dim VisEnable
If IsNull(Me.txtFirstName) Then
MsgBox ("Please add First Name for this Prospect")
Me.txtFirstName.SetFocus
Exit Sub
End If
If IsNull(Me.txtLastName) Then
MsgBox ("Please add Last Name for this Prospect")
Me.txtLastName.SetFocus
Exit Sub
End If
If IsNull(Me.cboIndustry) Then
Me.cboIndustry = ""
End If
If IsNull(Me.cboGeo) Then
Me.cboGeo = ""
End If
If IsNull(Me.cboInfluence) Then
Me.cboInfluence = ""
End If
If IsNull(Me.cboSchool) Then
Me.cboSchool = ""
End If
If IsNull(Me.cboTier) Then
Me.cboTier = ""
End If
If IsNull(Me.cboCompany) Then
Me.cboCompany = ""
End If
If IsNull(Me.txtTitle) Then
Me.txtTitle = ""
End If
If IsNull(Me.cboStatus) Then
Me.cboStatus = ""
End If
If IsNull(Me.cboOwner) Then
Me.cboOwner = ""
End If
If IsNull(Me.txtPhone) Then
Me.txtPhone = ""
End If
If IsNull(Me.txtEmail) Then
MsgBox ("Please add Email for this Prospect")
Me.txtEmail.SetFocus
Exit Sub
End If
If IsNull(Me.txtNotes) Then
Me.txtNotes = ""
End If
If IsNull(Me.txtInitialProspectEmailSentDate) Then
Me.txtInitialProspectEmailSentDate = ""
End If
If IsNull(Me.txtNextTouchPoint) Then
Me.txtNextTouchPoint = ""
End If
strFirstName = Me.txtFirstName
strLastName = Me.txtLastName
strIndustry = Me.cboIndustry
strCompany = Me.cboCompany
strTitle = Me.txtTitle
strStatus = Me.cboStatus
strPhone = Me.txtPhone
strEmail = Me.txtEmail
strNotes = Me.txtNotes
strOwner = Me.cboOwner
dtEmailSent = Me.txtInitialProspectEmailSentDate
dtNextTouchPoint = Me.txtNextTouchPoint
strRegion = Me.cboGeo
strSoR = Me.cboTier
strInfluence = Me.cboInfluence
strClient = Me.ckClient
strCoworker = Me.ckCoworker
strSchool = Me.cboSchool
strSQL = "Update tblProspect Set FirstName = " & """" & strFirstName & """" & ",LastName = " & """" & strLastName & """" & ",Industry = " & """" & strIndustry & """" & "" & _
",Geography = " & """" & strRegion & """" & ",StrengthofRelationship = " & """" & strSoR & """" & ",School = " & """" & strSchool & """" & ",Company = " & """" & strCompany & """" & "" & _
",Title = " & """" & strTitle & """" & ",Status = " & """" & strStatus & """" & ", InfluenceLevel = " & """" & strInfluence & """" & ", FormerClient = " & strClient & ", FormerCoWorker = " & strCoworker & "" & _
",Email = " & """" & strEmail & """" & ",Phone = " & """" & strPhone & """" & ",ProspectOwner = " & """" & strOwner & """" & ",Notes = " & """" & strNotes & """" & ""
If dtNextTouchPoint <> "" Then
strSQL = strSQL & " ,NextTouchPoint = #" & dtNextTouchPoint & "#"
End If
If dtEmailSent <> "" Then
strSQL = strSQL & " ,LastEmailDate = #" & dtEmailSent & "#"
End If
strSQL = strSQL & " WHERE Email = " & """" & strEmail & """" & ""
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
Dim ctl As Control
For Each ctl In Me.Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox, acListBox, acCheckBox
If ctl.ControlSource = "" Then
ctl.Value = Null
End If
Case Else
End Select
Next ctl
Me.Visible = False
DoCmd.OpenForm "frmProspectAdmin", acNormal, , , acFormEdit, acWindowNormal
DoCmd.RunCommand acCmdSaveRecord
Form_frmProspectProfile.Refresh
Form_frmProspectAdmin.Refresh
End Sub
It comes out exactly likely I want it to in Debug.Print, but it does not save that way in the contact profile.
Debug.Print strSQL
Update tblProspect Set FirstName = "Jon",LastName = "Snow",Industry = "Other",Geography = "",StrengthofRelationship = "",School = "",Company = "",Title = "",Status = "Dead", InfluenceLevel = "", FormerClient = 0, FormerCoWorker = 0,Email = "jsnow#winterfell",Phone = "",ProspectOwner = "",Notes = ""
I have a list of names in a subform, and on my main form I have a button that allows the user to view the "profile" of a given contact. Once in a profile, I would like there to be a button that allows the user to move to the next name in the subform (while staying the "profile" view) by clicking "next user".
In addition, the DB asks the user whether she/he wants to save changes (vbYesNo) to the profile before moving to the next user's profile. For some reason, my code works the when the user clicks "next contact" and "yes" the first time, but it will not scroll to the next contact each subsequent time the user clicks "next contact" and "yes". Note that the "next user" button works fine if the user selects "no" for when she/he does not want to save changes made to the profile.
Here is the code:
Private Sub Command65_Click()
Dim strFirstName As String
Dim strLastName As String
Dim strIndustry As String
Dim strCountry As String
Dim strState As String
Dim strCity As String
Dim strCompany As String
Dim strTitle As String
Dim strStatus As String
Dim strPhone As String
Dim strEmail As String
Dim strOwner As String
Dim DateNow As String
Dim rs As DAO.Recordset
'Allow user to leave some fields blank. User must fill in certain fields.
Dim VisEnable
intMsg = MsgBox("Would you like to save the current contact's information?", vbYesNo)
If intMsg = 6 Then
If IsNull(Me.txtFirstName) Then
MsgBox ("Please add First Name for this Prospect")
Me.txtFirstName.SetFocus
Exit Sub
End If
If IsNull(Me.txtLastName) Then
MsgBox ("Please add Last Name for this Prospect")
Me.txtLastName.SetFocus
Exit Sub
End If
If IsNull(Me.cboIndustry) Then
Me.cboIndustry = ""
Exit Sub
End If
If IsNull(Me.cboGeo) Then
Me.cboGeo = ""
End If
If IsNull(Me.cboInfluence) Then
Me.cboInfluence = ""
End If
If IsNull(Me.cboSchool) Then
Me.cboSchool = ""
End If
If IsNull(Me.cboTier) Then
Me.cboTier = ""
End If
If IsNull(Me.cboCompany) Then
Me.cboCompany = ""
End If
If IsNull(Me.txtTitle) Then
Me.txtTitle = ""
End If
If IsNull(Me.cboStatus) Then
Me.cboStatus = ""
Exit Sub
End If
If IsNull(Me.cboOwner) Then
Me.cboOwner = ""
End If
If IsNull(Me.txtPhone) Then
Me.txtPhone = ""
End If
If IsNull(Me.txtEmail) Then
MsgBox ("Please add Email for this Prospect")
Me.txtEmail.SetFocus
Exit Sub
End If
If IsNull(Me.txtNotes) Then
Me.txtNotes = ""
Exit Sub
End If
If IsNull(Me.txtInitialProspectEmailSentDate) Then
Me.txtInitialProspectEmailSentDate = ""
End If
If IsNull(Me.txtNextTouchPoint) Then
Me.txtNextTouchPoint = ""
End If
strFirstName = Me.txtFirstName
strLastName = Me.txtLastName
strIndustry = Me.cboIndustry
strCompany = Me.cboCompany
strTitle = Me.txtTitle
strStatus = Me.cboStatus
strPhone = Me.txtPhone
strEmail = Me.txtEmail
strNotes = Me.txtNotes
strOwner = Me.cboOwner
dtEmailSent = Me.txtInitialProspectEmailSentDate
dtNextTouchPoint = Me.txtNextTouchPoint
strRegion = Me.cboGeo
strSoR = Me.cboTier
strInfluence = Me.cboInfluence
strClient = Me.ckClient
strCoworker = Me.ckCoworker
strSchool = Me.cboSchool
strSQL = "Update tblProspect Set FirstName = " & """" & strFirstName & """" & ",LastName = " & """" & strLastName & """" & ",Industry = " & """" & strIndustry & """" & "" & _
",Geography = " & """" & strRegion & """" & ",StrengthofRelationship = " & """" & strSoR & """" & ",School = " & """" & strSchool & """" & ",Company = " & """" & strCompany & """" & "" & _
",Title = " & """" & strTitle & """" & ",Status = " & """" & strStatus & """" & ", InfluenceLevel = " & """" & strInfluence & """" & ", FormerClient = " & strClient & ", FormerCoWorker = " & strCoworker & "" & _
",Email = " & """" & strEmail & """" & ",Phone = " & """" & strPhone & """" & ",ProspectOwner = " & """" & strOwner & """" & ",Notes = " & """" & strNotes & """" & ""
If dtNextTouchPoint <> "" Then
strSQL = strSQL & " ,NextTouchPoint = #" & dtNextTouchPoint & "#"
End If
If dtEmailSent <> "" Then
strSQL = strSQL & " ,LastEmailDate = #" & dtEmailSent & "#"
End If
strSQL = strSQL & " WHERE Email = " & """" & strEmail & """" & ""
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
intRecord = Me.txtRecord + 1
Set rs = CurrentDb.OpenRecordset("qselProspects")
If rs.RecordCount <> 0 Then
rs.MoveLast
If intRecord = 1 Then
intRecord = rs.RecordCount + 1
End If
End If
If rs.RecordCount <> 0 Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
If intRecord = rs.AbsolutePosition Then
Me.txtRecord = intRecord
Me.txtFirstName = rs!FirstName
Me.txtLastName = rs!LastName
Me.txtTitle = rs!Title
Me.cboCompany = rs!Company
Me.cboIndustry = rs!Industry
Me.cboGeo = rs!Geography
Me.cboTier = rs!StrengthofRelationship
Me.cboIndustry = rs!InfluenceLevel
Me.cboSchool = rs!School
Me.ckClient = rs!FormerClient
Me.ckCoworker = rs!FormerCoWorker
Me.cboStatus = rs!Status
Me.cboOwner = rs!ProspectOwner
Me.txtEmail = rs!Email
Me.txtPhone = rs!Phone
Me.txtNextTouchPoint = rs!NextTouchPoint
Me.txtNotes = rs!Notes
Me.txtInitialProspectEmailSentDate = rs!LastEmailDate
End If
rs.MoveNext
Loop
End If
'''///If you choose No it works, but if you choose Yes it does not...very strange
Else
intRecord = Me.txtRecord + 1
Set rs = CurrentDb.OpenRecordset("qselProspects")
If rs.RecordCount <> 0 Then
rs.MoveLast
If rs.RecordCount = intRecord Then
intRecord = 0
End If
End If
If rs.RecordCount <> 0 Then
rs.MoveFirst
Do Until rs.EOF = True
If intRecord = rs.AbsolutePosition Then
Me.txtRecord = intRecord
Me.txtFirstName = rs!FirstName
Me.txtLastName = rs!LastName
Me.txtTitle = rs!Title
Me.cboCompany = rs!Company
Me.cboIndustry = rs!Industry
Me.cboGeo = rs!Geography
Me.cboTier = rs!StrengthofRelationship
Me.cboIndustry = rs!InfluenceLevel
Me.cboSchool = rs!School
Me.ckClient = rs!FormerClient
Me.ckCoworker = rs!FormerCoWorker
Me.cboStatus = rs!Status
Me.cboOwner = rs!ProspectOwner
Me.txtEmail = rs!Email
Me.txtPhone = rs!Phone
Me.txtNextTouchPoint = rs!NextTouchPoint
Me.txtNotes = rs!Notes
Me.txtInitialProspectEmailSentDate = rs!LastEmailDate
End If
rs.MoveNext
Loop
End If
End If
End Sub
Thanks to whoever can figure this out! This has eaten up too many hours as it is.
This is not an answer, but I write it here because it does not fit in a comment. A few advises that if you have applied, would have spared you all this head-ache.
1) your code follows the pattern
If User_Says_Yes Then
Save
Fetch_Next_Record
Else
Fetch_Next_Record
Endif
This is problematic because the Fetch_Next_Record is a lot of code and it is duplicated, and you spend a lot of time to see where it differs. duplicating code is generally a very bad idea. Try to rewrite it with the following pattern:
If User_Says_Yes Then
Save
Endif
Fetch_Next_Record
2) Try to make your code shorter, by moving as much as you can to private subroutines. for example, write some Function like BuildSQL() as String, a subroutine like updateFormFromRs(rs as Recordset). In General, when any of your routines or functions get too long, say more than 20 or 30 lines, you should think of migrating some code to subroutines and functions
3) Indent your code. It is so difficult to follow your code without it.. just to see where was the Else that starts when the user says no...
4) You fetch a whole table in the recordset, just to scroll it and find one record to display that matches if intRecord = rs.AbsolutePosition? Why not use a SQL statement with a WHERE clause and load just the desired record? This is something you need to apply in any serious application with a decent amount of data.
5) statements like If rs.EOF = True Then: Simply If rs.EOF Then.
The additional = True will not make the test more strict whatsoever. as if without it we check if the condition was almost true.
Finally, even if you have possibly inherited this code from someone else, I am sure that you will have to rewrite it completely and improve it, the sooner the better. And yes, I am sure that if you follow these guidelines, you will be able to debug you code very easily.
Friendly :)
I need your help. I woulod like to change one char by another but in all database and i have several table and fields. So i'm building a function in VB but that change nothing and i have no error. I think that my condition is false but i don't see how to correct it :/
Public Sub updateField()
Dim db As DAO.Database, td As DAO.TableDef, field As DAO.field
Dim rs As DAO.Recordset, sSQL As String, sData As String
Set db = CurrentDb
Change = "\"""
replaced = """"
'each table in db
For Each tbd In db.TableDefs
'each field in table
For Each fld In tbd.Fields
'check if String Data have my character
If InStr(1, fld.Name, Change) Then
sSQL = "UPDATE " & tbd.Name & " SET " & fld.Name & " = replace([" & fld.Name & "], " & Change & ", " & replaced & ")"
db.Execute sSQL
End If
Next
Next
End Sub
EDIT :
I finally find what's wrong. if some people are interested :
Set db = CurrentDb
Change = "\"""
replaced = """"
'each table in db
For Each tbd In db.TableDefs
'each field in table
For Each fld In tbd.Fields
If Left(tbd.Name, 4) <> "MSys" And Left(tbd.Name, 4) <> "~TMP" Then
If fld.Type = dbText Or fld.Type = dbMemo Then
sSQL = "UPDATE " & tbd.Name & " SET " & fld.Name & " = replace([" & fld.Name & "],'" & Chr(92) + Chr(34) & "','" & Chr(34) & "')"
db.Execute sSQL
'Debug.Print (sSQL)
End If
End If
Next
Next
Thx for your help guys ;)
If it should help there my solution :
Public Sub updateField()
Dim db As DAO.Database, td As DAO.TableDef, field As DAO.field
Dim rs As DAO.Recordset, sSQL As String, sData As String, change As String, replace As String
change = "\'"
replace = "'"
' simple quote = 39
' doulbe quote = 34
' antislash = 92
' retour chariot = 13
' n = 110
' r = 114
Set db = CurrentDb
'each table in db
For Each tbd In db.TableDefs
'each field in table
For Each fld In tbd.Fields
If Left(tbd.Name, 4) <> "MSys" And Left(tbd.Name, 4) <> "~TMP" Then
If fld.Type = dbText Or fld.Type = dbMemo Then
' \r\n
'sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'\r\n','" & Chr(13) & Chr(10) & "');"
' \"
'sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'" & Chr(92) + Chr(34) & "','" & Chr(34) & "');"
'db.Execute sSQL
sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'\''','''');"
db.Execute sSQL
'Debug.Print (sSQL)
End If
End If
Next
Next
End Sub
That's works for me ;)