根据Access中字段的值更改关系

时间:2016-11-21 22:18:30

标签: vba ms-access

我有一个表,我想连接其他三个表,我意识到这是不可能的,所以我决定找到一种方法来使用VBA。我抓住了一些我真正希望能够运行的代码并且一直在编辑它以使其能够满足我的特定需求

Option Compare Database

 Function changeRel()

    If Players.Cond = "Quest" Then
        Dim dbs As DAO.Database
        Dim rel As DAO.Relation

        Set dbs = CurrentDb

        Set rel = dbs.CreateRelation("QuestRel", "Players", "Player Quests", dbRelationDeleteCascade)
        rel.Fields.Append rel.CreateField("PlayerID")
        rel.Fields("PlayerID").ForeignName = "PQuestID"

        dbs.Relations.Append rel
        dbs.Relations.Refresh

    ElseIf Players.Cond = "Level" Then
        Dim dbs As DAO.Database
        Dim rel As DAO.Relation

        Set dbs = CurrentDb

        Set rel = dbs.CreateRelation("LevelRel", "Players", "Player Levels", dbRelationDeleteCascade)
        rel.Fields.Append rel.CreateField("PlayerID")
        rel.Fields("PlayerID").ForeignName = "PLevelID"

        dbs.Relations.Append rel
        dbs.Relations.Refresh

    ElseIf Players.Cond = "Stat" Then
        Dim dbs As DAO.Database
        Dim rel As DAO.Relation

        Set dbs = CurrentDb

        Set rel = dbs.CreateRelation("StatRel", "Players", "Player Stats", dbRelationDeleteCascade)
        rel.Fields.Append rel.CreateField("PlayerID")
        rel.Fields("PlayerID").ForeignName = "PStatsID"

        dbs.Relations.Append rel
        dbs.Relations.Refresh

    Else
        'Do nothing

End Function

我之前从未在VBA中编码,我不知道Option Compare Database意味着什么,它就在那里。我很确定我需要一个子程序,虽然我对它是什么感到困惑。

有人可以告诉我如何在每次单元格Players.Cond的值发生变化时运行此函数吗?

1 个答案:

答案 0 :(得分:0)

这样的事情如何从所有4个表中提取相关数据:

SELECT Players.PlayerID, [Player Quests].PQuestID, [Player Levels].PLevelID, [Player Stats].PStatsID
FROM (((Players 
  LEFT JOIN [Player Quests] ON Players.PlayerID = [Player Quests].PQuestID) 
  LEFT JOIN [Player Levels] ON Players.PlayerID = [Player Levels].PLevelID) 
  LEFT JOIN [Player Stats] ON Players.PlayerID = [Player Stats].PStatsID)