A funcionalidade abaixo permite automatizarmos a criação de relacionamentos entre tabelas.
Public Function CreateAllRelations()Dim db As DAO.DatabaseDim totalRelations As IntegerSet db = CurrentDb()Let totalRelations = db.Relations.CountIf totalRelations > 0 ThenFor i = totalRelations - 1 To 0 Step -1db.Relations.Delete (db.Relations(i).Name)Next iDebug.Print Trim(Str(totalRelations)) + " Relacionamentos deletados!"End IfDebug.Print "Criando Relacionamentos..."''Exemple'Relacionando Employee Master com Employee CheckInDebug.Print CreateRelation("Employee", "Code", _"CheckIn", "Code")' Relacionando Orders com Order DetailsDebug.Print CreateRelation("Orders", "No", _"OrderDetails", "No")totalRelations = db.Relations.CountSet db = NothingDebug.Print Trim(Str(totalRelations)) + " Relacionamentos criados!"Debug.Print "Completado!"End FunctionPrivate Function CreateRelation(primaryTableName As String, _primaryFieldName As String, _foreignTableName As String, _foreignFieldName As String) As BooleanOn Error GoTo ErrHandlerDim db As DAO.DatabaseDim newRelation As DAO.RelationDim relatingField As DAO.FieldDim relationUniqueName As StringLet relationUniqueName = primaryTableName + "_" + primaryFieldName + _"__" + foreignTableName + "_" + foreignFieldNameSet db = CurrentDb()'Argumentos para CreateRelation(): Qualquer nome único,' Tabela primária, tabela relacionada, atributos.Set newRelation = db.CreateRelation(relationUniqueName, _primaryTableName, foreignTableName)' O campo da tabela primária.Set relatingField = newRelation.CreateField(primaryFieldName)Let relatingField.ForeignName = foreignFieldNamenewRelation.Fields.Append relatingFielddb.Relations.Append newRelationSet db = NothingLet CreateRelation = TrueExit Function
ErrHandler:Debug.Print Err.Description + " (" + relationUniqueName + ")"CreateRelation = FalseEnd Function
Tags: VBA, Access, relations,
Nenhum comentário:
Postar um comentário