For Each qdf In db.QueryDefs
If Mid(qdf.Name, 1, 1) <> "~" Then
better would be if you know the names of the fields that was removedI'm dealing with a (linked SQL table) that has few hundred fields, and created a view with only half of them, so listing all fields would not be an option, what other way can I get the error message?
Public Sub AllQueriesWorking()
Dim db As Database, qdf As QueryDef, i As Integer, a As String, rs As Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset("testingquerymrb")
On Error Resume Next
For Each qdf In db.QueryDefs
If Mid(qdf.Name, 1, 1) <> "~" Then
i = i + 1
a = qdf.Name & ": " & DCount("*", "[" & qdf.Name & "]")
If Len(a) > 0 Then
rs.AddNew
rs("q1") = a
rs.Update
End If
End If
Next qdf
' MsgBox "finish Updating", vbInformation
End Sub
I'm currently running it, however not sure if that's accurate and its taking forever..set rs=db.openrecordset("qry1"I get no error when opening a query referencing those fields.)
' see what error it will raised.
Querydefs with a name starting with "~" should NOT be bypassed...You right, in a FE app this would definitely be the case and perhaps I should apply that when I will perform the testing to my FE application, however I'm currently testing a file which only contains queries, and therefore that was put in place.
so, there is only one table that was change, right?yes
where are the queries based, on the linked table or view?there were on the table, however I just created a view with only the needed fields and linked to Access and renamed as the table name..
are the queries have joins ?there are all types, some are based on joins.
Public Sub UllQueriesWorking()
Dim db As Database, qdf As QueryDef, i As Integer, a As String, rs As Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset("testingquerymrb")
On Error Resume Next
For Each qdf In db.QueryDefs
If Mid(qdf.Name, 1, 1) <> "~" Then
i = i + 1
a = qdf.Name & ": " & DCount("*", "[" & qdf.Name & "]")
If Len(a) > 0 Then
rs.AddNew
rs("q1") = a
rs.Update
End If
End If
Next qdf
End Sub
Sub getQueriesAndFields()
Dim rs As dao.Recordset, rs2 As dao.Recordset
Dim db As dao.Database, qd As dao.QueryDef
Dim oSql As String, sSql As String, j As Integer, i As Integer
Dim strTable As String, strFields As String
Dim tblFldArr() As String, qryFldArr() As String, qryFld As String
Dim blnFieldFound As Boolean
Set db = CurrentDb
strTable = "NewViewName" '<<< change with actual name
Set rs2 = db.OpenRecordset("Select * from NewViewName where 1=0") '<<< change with actual name
For j = 0 To rs2.Fields.Count - 1
strFields = strFields & ";" & rs2(j).Name
Next
strFields = Mid(strFields, 2)
tblFldArr = Split(strFields, ";")
For Each qd In db.QueryDefs
oSql = qd.sql
If InStr(oSql, strTable) Then
sSql = Left(oSql, InStr(oSql, "From") - 1)
sSql = Trim(Mid(sSql, InStr(sSql, " ")))
qryFldArr = Split(sSql, ",")
For j = 0 To UBound(qryFldArr)
If Trim(Left(qryFldArr(j), InStr(qryFldArr(j) & ".", ".") - 1)) = strTable Then
qryFld = Mid(qryFldArr(j), InStr(qryFldArr(j), ".") + 1)
'look for the qryFld in tblFldArr
blnFieldFound = False
For i = 0 To UBound(tblFldArr)
If tblFldArr(i) = qryFld Then
blnFieldFound = True
Exit For
End If
Next
If blnFieldFound = False Then
Debug.Print qd.Name
Debug.Print qryFld & " is not in " & strTable
End If
End If
Next
End If
Next
rs.Close
rs2.Close
Set db = Nothing
End Sub
The ADO and DAO libraries share several objects so declaring objects that appear in both libraries without disambiguating them, causes reference issues.I dont have reference issues as only DAO is referenced.
2. errors are ignored which is what is causing the duplication.The "a= xxx" throws an error when the query is an action query and so the value of a doesn't change. Â It just gets added to the table.No, the else portion gets executed, see attached. (I tried that).
3. I'm not sure what counting the rows of a table has to do with the problem you are trying to solveAs you can see on attached, this is when len(a)>0 gets false, so its serving the purpose..
4. You are ignoring relevant queries by bypassing any query whose name starts with ~.As mentioned, I will take this into consideration when testing other objects, at this point I'm only concerning about queries.
strTable = "NewViewName" '<<< change with actual name
Set rs2 = db.OpenRecordset("Select * from NewViewName where 1=0") '<<< change with actual name
strTable = "Employeestbl" '<<< change with actual name
Set rs2 = db.OpenRecordset("Select * from Employeestbl where 1=0", dbReadOnly, dbSeeChanges = True) '<<< change with actual name
Thanks,SELECT DISTINCTROW Employeestbl.Title, Employeestbl.LastName, Employeestbl.FirstName, Employeestbl.AddressLine1, Employeestbl.AddressLine2, Employeestbl.State, Employeestbl.Zip, Employeestbl.City, Employeestbl.County, TovInfo.Day, TovInfo.Facility1, [Emoloyee'sFacilitiestbl].FacilitieID, Employeestbl.Workphone
FROM TovInfo RIGHT JOIN (Facilitiestbl INNER JOIN (Employeestbl INNER JOIN [Emoloyee'sFacilitiestbl] ON Employeestbl.ID = [Emoloyee'sFacilitiestbl].EmployeeID) ON Facilitiestbl.ID = [Emoloyee'sFacilitiestbl].FacilitieID) ON TovInfo.EmployeeID = Employeestbl.ID
WHERE (((Employeestbl.Title)="rn") AND ((Employeestbl.AddressLine1) Is Not Null) AND (([Emoloyee'sFacilitiestbl].FacilitieID)=182)) OR (((Employeestbl.Title)="rn") AND ((Employeestbl.AddressLine1) Is Not Null) AND (([Emoloyee'sFacilitiestbl].FacilitieID)=181)) OR (((Employeestbl.Title)="rn") AND ((Employeestbl.AddressLine1) Is Not Null) AND ((Employeestbl.Workphone) Like "(212) 318*"))
ORDER BY Employeestbl.Title DESC , Employeestbl.LastName;
your code is showing For j = 0 To rs2.Fields.Count - 1
strFields = strFields & ";" & rs2(j).Name
Next
strFields = Mid(strFields, 2)
Debug.Print strFields
I see nothing ID;AclsExpires;AclsLetterDate;AclsSignedYN;AddFederal;AddressLine1;AddressLine2;Application;AttestationFormDate;AttestationFormSigned;AvailibilityPDate;AvailibilityPDays;AvailibilityPShifts;BackgroundAgency;BackgroundCheck;BackgroundCheckConsent;BackgroundCheckDate;BackgroundCheckResults;BclsExpires;BclsLetterDate;BclsSignedYN;Beeper;BeeperExt;BestTimeToReach;Bilingual;Birthdate;Chauncey_Date;Chauncey_Results;ChauncySanctionsDate;ChauncySanctionsResults;ChestXRayDate;ChestXRayRes;City;COIDate;CoreMandatory;CoreMandatoryDate;CorporateCompliancePolicyDate;County;CPIDate;CPR;CriminalPerApp;Degree;DocumentsYesNo;DriveYN;DrugScreen;DuplicateYN;EducationVerified;Email;Email2;EmailAddressInvalid;EmailLastVerifiedDate;EmailLastVerifiedInitial;EmailVerifiedByVendorDate;EmpCode;EmployeeStatus;EmployeeStatusDate;EmployeeStatusInitial;EmpPassword;EmpUserName;EthnicGroup;EVerifyYN;Exemptions;ExpectedGraduation;ExpectedGraduationDate;Extension;FacilityCompleted;FacilityCompletedDate;FacilityCompletedInitial;FileCompleted;
FileCompleteDate;FileCompleteInitial;FirstName;FluAttestationFormDate;FluExempt;FluShutDate;H1n1;HasSpecialtyLicenses_HHA;HasSpecialtyLicenses_ORT;HasSpecialtyLicenses_PCA;HasSpecialtyLicenses_PCT;HepBLabReports;HepBRes;HepBTiter;HepBVac;HepBWaiver;HIPAADate;HireDate;HomeAddressLine1;HomeAddressLine2;HomeCareExamsDueDate;HomeCity;HomePhone;HomeState;HomeZip;I9Complete;ID_A;ID_A_Expires;ID_B;ID_B_Expires;ID_C;Initial;IntrestedinVAFacilities;LastName;LicenseExpires;LicenseNum;LicenseNumSignedYN;LicenseState;LSFormYN;LSOnApplyingDate;MalLevelOK;MalpracticeCompany;MalpracticeExpires;MalpracticePolicyNo;MaritalStatus;MaskFitTestDate;MeaslesRubeolaDate;MeaslesRubeolaLabReports;MeaslesRubeolaRes;MeaslesRubeolaTiter;MedicalClearanceYN;MiddleInitial;MumpsDate;MumpsLabReports;MumpsRes;MumpsTiter;NalsExpires;NalsSignedYN;NoNightCalls;NotAvailChecked;NotAvailUntil;Note;NotSendEmail;NotSendMassEmail;NotSendMassTextMsg;NotSendTextMsg;NPI;OmigOigSamDate;OmigOigSamRes;Online;OP_Date;OP_Results;OrientationCheckList;Orientati
onDocumentationFacility;ORTResults;ORTVerificationDate;Paid;PaidInitial;PalsExpires;PalsLetterDate;PalsSignedYN;Performance_Eval_Comp;PhisycalPPD_Date;PhisycalPPD_Res;Phone2;Physical;PPD2ndStepDate;PPD2ndStepRes;Print_Label;RecOfEmploy;Reference1;Reference2;References1Date;References1Initial;References2Date;References2Initial;ReferredBy;ReferredByDate;ResumeYN;ResumeYNDate;ResumeYNInitial;RubellaDate;RubellaLabReports;RubellaRes;RubellaTiter;SanctionsDate;SanctionsResults;Scanner;Sex;SizeModel;SkillsChecklist;SkillsChecklistDate;SkillsChecklistScore;SkillsChecklistScore2;SkillsChecklistUnit1;SkillsChecklistUnit2;SMSProvider;SMSProviderLastVerifiedDate;SocialSecurityNumber;SSAYN;State;TaxCredit8850;TaxCredit8850YN;TBQDate;TBQResults;TestYN;Tetanus;Title;Title2;TravelerYN;Urinalysis;VaricellaDate;VaricellaLabReports;VaricellaRes;VaricellaTiter;VentTrainingClass;veteran;VolSelfID;W4;W4Date;WGDrugScreenDate;WGIDStatus;WGRecordsDate;WGRecordsInitial;WGRecordsYN;Workphone;Zip;SMSProviderInvalid
I dont have reference issues as only DAO is referenced.Obviously, or you would have fixed them. Â The database I had open when I pasted in the code had both DAO and ADO references so I had trouble. Â Use Good Practice. Â ALWAYS disambiguate. Â That way if someone (or yourself) later adds code for the "other" library, existing code won't fail.
No, the else portion gets executed, see attached. (I tried that)This line fails for action queries.  If you step through the code you will see it.  Then the code continues with the next line because of ---- On Error Resume Next  --- that is what is causing the duplicates.
As you can see on attached, this is when len(a)>0 gets false, so its serving the purposeYou are running a different procedure than what you posted
As mentioned, I will take this into consideration when testing other objects, at this point I'm only concerning about queries.For other objects it doesn't matter. Â It is only queries where Access helps you out and makes queries for you. The highlighted queries are QUERYDEFS that Access made for me because I put SQL strings into combos.
This line fails for action queries.  If you step through the code you will see it.  Then the code continues with the next line because of ---- On Error Resume Next  --- that is what is causing the duplicates.Regardless it should not be creating duplicate entries per query as the for each..next loops for the next query, and there is only one insert in the loop body.
You are running a different procedure than what you postedNot sure what you're referring to?
For other objects it doesn't matter. Â It is only queries where Access helps you out ..I meant to say, in this file there are not forms or reports only queries, so this is why its not necessary to include the hidden queries here.
Sub getQueriesAndFields1()
Dim rs As dao.Recordset, rs2 As dao.Recordset
Dim db As dao.Database, qd As dao.QueryDef
Dim oSql As String, sSql As String, j As Integer, i As Integer
Dim strTable As String, strFields As String
Dim tblFldArr() As String, qryFldArr() As String, qryFld As String
Dim blnFieldFound As Boolean
Set db = CurrentDb
strTable = "Employeestbl" '<<< change with actual name
Set rs2 = db.OpenRecordset("Select * from Employeestbl where 1=0", dbReadOnly)
For j = 0 To rs2.Fields.Count - 1
strFields = strFields & ";" & rs2(j).Name
Next
strFields = Mid(strFields, 2)
tblFldArr = Split(strFields, ";")
For Each qd In db.QueryDefs
oSql = qd.SQL
If InStr(oSql, strTable) Then
sSql = Left(oSql, InStr(oSql, "From") - 1)
sSql = Trim(Mid(sSql, InStr(sSql, " ")))
qryFldArr = Split(sSql, ",")
For j = 0 To UBound(qryFldArr)
If Trim(Left(qryFldArr(j), InStr(qryFldArr(j) & ".", ".") - 1)) = strTable Then
qryFld = Trim(Mid(qryFldArr(j), InStr(qryFldArr(j), ".") + 1))
qryFld = Replace(qryFld, "[", "")
qryFld = Replace(qryFld, "]", "")
'look for the qryFld in strFields
If InStr(";" & strFields & ";", ";" & Replace(qryFld, vbCrLf, "") & ";") Then
'do nothing
Else
If InStr(qryFld, " as ") Then
If InStr(";" & strFields & ";", ";" & Replace(Mid(qryFld, 1, InStr(qryFld, " as ") - 1), vbCrLf, "") & ";") Then
Else
Debug.Print qd.Name & " - "; Replace(qryFld, vbCrLf, "") & " is not in " & strTable
End If
Else
Debug.Print qd.Name & " - "; Replace(qryFld, vbCrLf, "") & " is not in " & strTable
End If
End If
End If
Next
End If
Next
rs2.Close
Set db = Nothing
End Sub
Now wondering, since there is a big list and the debug window can not keep all the info, how can I run this loop in separate lists, like first only till letter "E", and then continue till letter...?
set db=currentdb()
  For Each qdf In db.QueryDefs
    If Mid(qdf.Name, 1, 1) <> "~" Then
      debug.print qdf.name
    end if
  next
better would be if you know the names of the fields that was removed and put them in an array.
iterate through the array to find which query uses them with
for j=0 to ubound(arrField)
 if instr(qdf.sql, arrField(j)) then
  ...