Sie sind auf Seite 1von 4

12/7/2016

passingAccess.Applicationobjecttoafunction:Dim,Set,Objecthowtomakeitwork?StackOverflow

StackOverflowisacommunityof4.7
millionprogrammers,justlikeyou,
helpingeachother.

signup

login

tour

help

JointheStackOverflowcommunityto:

Jointhemitonlytakesaminute:
Signup

Askprogramming
questions

Answerandhelp
yourpeers

Getrecognizedforyour
expertise

passingAccess.Applicationobjecttoafunction:Dim,Set,Objecthowtomakeitwork?

Icameuponthis(modified)functioninaStackOverflowpageandhavebeentryingtogetittoworkwithoutgivinguponthepassedobject(ifI
handlethe Access.Application strictlywithinthefirstroutineitwillwork).
YesIknowofanumberofwaystogetthesameanswer(mostlyfromotherpostsonthestack),butthereisageneralconcepthereof
passingobjectstofunctionsthatIwouldliketomasterpleaseforgetforamomentthatthefunctioncheckstheexistenceofatable.
FunctionFCN_CheckTblsExist(theDatabaseAsAccess.Application,_
tableNameAsString)AsBoolean
'access.Application.CurrentData.AllTables.Count
'etcisthe'workaroundenablingdisposalof
'the"theDatabase"objectvariable
'Presumethattabledoesnotexist.
FCN_CheckTblsExist=False
'Defineiteratortoquerytheobjectmodel.
DimiTableAsInteger
'Loopthroughobjectcatalogueandcomparewithsearchterm.

ForiTable=0TotheDatabase.CurrentData.AllTables.Count1
IftheDatabase.CurrentData.AllTables(iTable).Name=tableNameThen
FCN_CheckTblsExist=True
ExitFunction
EndIf
NextiTable

EndFunction

FunctioncallFCN_CheckTblsExist(tableNameAsString)
'thisisanexampleofacurriedfunction?stepdownindimensionality
Dimbo0AsString
DimAAsObject
SetA=CreateObject("Access.Application")
bo0=FCN_CheckTblsExist(A,tableName)
MsgBoxtableName&"Existsis"&bo0
EndFunction

Idon'tknowifthe( theDatabaseAsAccess.Application, .)partiscorrect,thatmaybetherootoftheproblem,ratherthantheDim,Set,Object


(New?)gymnasticsthatmayberequiredintheauxiliaryprocedure.Maybethereisareferencelibraryproblem(I'mrunningAccess2013).
Update:IamnotsurethefollowingisrobustenoughbutthisiswhatImeantearlierinthepost,whichisjustbeingputhereforcompleteness.
BTW,thisisnotasplitapplicationsomaybethatiswhythefollowingworks.IappreciateHansUp'spost,Notenoughcanbesaidonthissubject.
Anyway
PublicFunctionFCN_CheckTblsExist(tableNameAsString)AsBoolean'Callthisfunction
onceforeverytable
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
DimappAccessAsNewAccess.Application
DimtheDatabaseAsAccess.Application
'Presumethattabledoesnotexist.
FCN_CheckTblsExist=False
'Defineiteratortoquerytheobjectmodel.
DimiTableAsInteger
ForiTable=0ToAccess.Application.CurrentData.AllTables.Count1
IfAccess.Application.CurrentData.AllTables(iTable).Name=tableNameThen
FCN_CheckTblsExist=True
ExitFunction
EndIf

http://stackoverflow.com/questions/31395279/passingaccessapplicationobjecttoafunctiondimsetobjecthowtomakeit

1/4

12/7/2016

passingAccess.Applicationobjecttoafunction:Dim,Set,Objecthowtomakeitwork?StackOverflow

NextiTable
EndFunction

JustwantedtoaddthatthislastfunctionIpostedtechnicallywouldbeconsideredtobepartialornocurryingdependingonhowmuchthescope
ofthefunctionwaslimitedbyinvoking"Access.Application.CurrentData.AllTables."asasubstitutefor"theDatabase",onlysubstitutingthe
specificstringcreatedbyAccess.Application.CurrentDb.Nameintotheoriginalfunction...(theDatabse,...woulditbeatruefullcurrying.
Anywaypassingobjectstofunctionsandthelibrariesandtheirmethodsaretheprimaryfocusofthisdiscussion.WhenIgettheDAOissue
workedishouldhaveabetterfeelforwhatmaybegoingonandthenI'llpostandmarkthebestsolutionaccordingly.
msaccess accessvba passbyreference currying
editedJul14'15at19:38

askedJul13'15at23:41

StumpedObject
25

2Answers

Theproblemisnotreallyaboutpassingan Access.Application objecttoyourotherfunction.


Insteadyoucreatethe Access.Application andlatercheckfortheexistenceofatablewithout
havingopenedadatabasewithinthatAccesssession.Inthatsituation,
theDatabase.CurrentData.AllTables.Count shouldtriggererror2467,"Theexpressionyouentered
referstoanobjectthatisclosedordoesn'texist."
IrevisedbothproceduresandtestedtheminAccess2010.Bothcompileandrunwithouterrors
andproducetheresultIthinkyouwant.
FunctionFCN_CheckTblsExist(theDatabaseAsAccess.Application,_
tableNameAsString)AsBoolean
DimtdfAsDAO.TableDef
DimblnReturnAsBoolean
blnReturn=False
ForEachtdfIntheDatabase.CurrentDb.TableDefs
Iftdf.Name=tableNameThen
blnReturn=True
ExitFor
EndIf
Next'tdf
FCN_CheckTblsExist=blnReturn
EndFunction
FunctioncallFCN_CheckTblsExist(DbPathAsString,tableNameAsString)
Dimbo0AsBoolean
DimAAsObject
SetA=CreateObject("Access.Application")
A.OpenCurrentDatabaseDbPath
bo0=FCN_CheckTblsExist(A,tableName)
MsgBoxtableName&"Existsis"&bo0
Debug.PrinttableName&"Existsis"&bo0
A.Quit
SetA=Nothing
EndFunction

NoteIdidn'tincludeanyprovisiontocheckwhethertheDbPathdatabaseexistsbefore
attemptingtoopenit.Soyouwillgetanerrorifyougiveitapathforadatabasewhichdoesnot
exist.
DAOReferenceIssues:
DAO3.6wasthelastoftheolderDAOseries.ItonlysupportstheolderMDBtypedatabases.
WhenAccess2007introducedtheACCDBdatabasetype,anewDAOlibrary(Accessdatabase
engineObjectLibrary ,sometimesreferredtoasACEDAO)wasintroduced.Inadditionto
supportingACCDBdatabases,ACEDAOcanalsosupporttheolderMDBtypes.
Whensettingreferences,don'tattempttochooseboth.
Hereisascreenshotofmyprojectreferences:

http://stackoverflow.com/questions/31395279/passingaccessapplicationobjecttoafunctiondimsetobjecthowtomakeit

2/4

12/7/2016

passingAccess.Applicationobjecttoafunction:Dim,Set,Objecthowtomakeitwork?StackOverflow

WhenIexaminemyprojectreferencesintheImmediatewindow,noticethatACEDAOiseven
referredtoasjustDAO.IalsoranthecallFCN_CheckTblsExistproceduretodemonstrateit
workswithoutaDAO3.6reference:

ThatwasallbasedonAccess2010.You'reusingAccess2013,soyourACEDAOversion
numbermaybedifferent,buteverythingelseshouldbethesame.
editedJul14'15at20:34

answeredJul14'15at4:00

HansUp
77.7k

11

42

70

Iamgettingaruntimeerroronline="ForEachtdfIntheDatabase.CurrentDb.TableDefs",Itriedtoload

DAO3.6 StumpedObject Jul14'15at5:41


Gettingaruntimeerroronline="ForEachtdfIntheDatabase.CurrentDb.TableDefs",ItriedtoloadDAO3.6

objectlibrary,thatmaybemyproblem,Ihavethefollowingreferencesavailable:vba,msaccess15.9
objectL,OLEAutom,MSOffice15.0AccessDBengine,MicrosoftActiveXDataObjects2.8L.Itriedit
withafullstringforthedatabasespathandname,alsowithaccess.application.CurrentDb.Nameinlieuof
thethestringnosuccess.Iamafraidthatmaybethereisbadconflictwiththereferencelibrarysaythis
becauseusuallyIgetawarningbutthereferenceisstillallowed StumpedObject Jul14'15at5:53
RemovetheDAO3.6objectlibraryreference.TheAccessdatabaseengineobjectlibraryprovidesDAO

features.HansUpJul14'15at11:42

Hereareacoupleofsolutionsalongwithamuchsimplerwaytocheckifatable
exists:
Workspace/Database(muchfasterthanusingApplication)
FunctionTestFunction_DataBase()
DimwsAsWorkspace
DimdbAsDatabase
Setws=CreateWorkspace("","admin","","dbUseJet")
Setdb=ws.OpenDatabase("thedbpath",,,CurrentProject.Connection)

http://stackoverflow.com/questions/31395279/passingaccessapplicationobjecttoafunctiondimsetobjecthowtomakeit

3/4

12/7/2016

passingAccess.Applicationobjecttoafunction:Dim,Set,Objecthowtomakeitwork?StackOverflow

MsgBoxTdefExists_DataBase(db,"thetablename")
db.Close
ws.Close
Setdb=Nothing
Setws=Nothing
EndFunction
FunctionTdefExists_DataBase(acAsDatabase,strTableNameAsString)AsBoolean
'checktoseeiftableexists
OnErrorGoToErrHandler
DimstrBSAsString
strBS=ac.TableDefs(strTableName).Name
TdefExists_DataBase=True
ExitFunction
ErrHandler:
TdefExists_DataBase=False
EndFunction

Application:
FunctionTestFunction_Application()
DimacAsNewAccess.Application
ac.OpenCurrentDatabase"thedbpath"
MsgBoxTdefExists_Application(ac,"thetablename")
ac.Quit
Setac=Nothing
EndFunction
FunctionTdefExists_Application(acAsAccess.Application,strTableNameAsString)As
Boolean
'checktoseeiftableexists
OnErrorGoToErrHandler
DimstrBSAsString
strBS=ac.CurrentDb.TableDefs(strTableName).Name
TdefExists_Application=True
ExitFunction
ErrHandler:
TdefExists_Application=False
EndFunction

WithintheCurrentDatabase:
FunctionTdefExists(strNameAsString)AsBoolean
'checktoseeifqueryexists
OnErrorGoToErrHandler
DimstrBSAsString
strBS=CurrentDb.TableDefs(strName).Name
TdefExists=True
ExitFunction
ErrHandler:
TdefExists=False
EndFunction
answeredJul14'15at17:41

PractLogical
226

http://stackoverflow.com/questions/31395279/passingaccessapplicationobjecttoafunctiondimsetobjecthowtomakeit

4/4

Das könnte Ihnen auch gefallen