0

このクエリで表すことができる 2 つのテーブルがあります (このクエリをフォームのレコードソースにしました)。

SELECT tblrcmtask.id, tblrcmtask.rcmtask,tblrcmtaskoptions.id, 
tblrcmtaskoptions.rcm_id,
tblrcmtaskoptions.rcmtaskoptions 
FROM tblrcmtask 
INNER JOIN tblrcmtaskoptions 
ON tblrcmtask.id=tblrcmtaskoptions.rcm_id 

Access 2007 のフォームを使用して、ユーザーがこれらのテーブルに新しいエントリを追加できるようにしたいと考えています。列tblrcmtask.idおよびは、それぞれテーブルおよびtblrcmtaskoptions.idの主キーです。ユーザーが新しいエントリを追加している間に、両方のテーブルに新しい ID を作成する方法がわかりません。ユーザーは、tblrcmtaskoptions.rcmtaskoptions と tblrcmtask.rcmtask のみをフォームに追加できます。また、各 tblrcmtask のテーブル tblrcmtaskoptions には複数の行があります。 .id. ユーザーが既存の tblrcmtask.id のテーブル tblrcmtaskoptions に新しい行を追加できるようにしたいtblrcmtasktblrcmtaskoptions

これら 2 つのドロップダウンを使用してみましたが、ID の最大値 + 1 として新しい ID を作成するときに問題に直面しています。

Dim MyRecords As DAO.Recordset 
Dim Myfield As DAO.Fields 
SQL = "SELECT Max(tblRCMTASK.ID) AS MaxOf_RCMTASKID FROM tblRCMTASK;" 
Set MyRecords = dbTHIS.OpenRecordset(SQL) 
Set Myfield = MyRecords.Fields 
Me.txtRCMTASKID = Myfield("MaxOf_RCMTASKID") + 1 
Me.txtRCMTASKID.DefaultValue = Myfield("MaxOf_RCMTASKID") + 1 
MyRecords.Close 
End If 
Dim MyRecords1 As DAO.Recordset 
Dim Myfield1 As DAO.Fields 
SQL = "SELECT Max(tblRCMTASKOPTIONS.ID) AS MaxOf_RCMOPTIONSID FROM tblRCMTASK;" 
Set MyRecords = dbTHIS.OpenRecordset(SQL) 
Set Myfield1 = MyRecords1.Fields 
Me.txtRCMOPTIONSID = Myfield1("MaxOf_RCMOPTIONSID") + 1 
Me.txtRCMOPTIONSID.DefaultValue = Myfield("MaxOf_RCMOPTIONSID") + 1 
MyRecords1.Close

このオブジェクトに値を代入できないというエラーが表示され、次の行を指しています: Me.txtRCMTASKID = Myfield("MaxOf_RCMTASKID") + 1

どうすればいいですか?

4

2 に答える 2

1

オートナンバーフィールドで操作を行おうとすると、Accessで問題が発生します。このような操作をしたい場合は、PKとして通常の番号を使用する方がよい場合があります。

最近挿入された自動番号フィールドを取得して、関連するテーブルに同じ番号を挿入するには、これがVBAです。

レコードセットとデータベースが宣言されていると仮定すると、rsとdb

     dim id as integer
     set db = CurrentDb
     set rs = db.openrecordset("firstTable", dbOpenDynaSet)
 With rs
   .addNew
   .Fields("field1").Value = Me.control1   'adds to column1 of your table the value of control1
   .Fields("field2").Value = Me.control2
   .update                                 'updates the record. If it is an autonumber, it will be automatically assigned. I will show you how to access this for your next insert
 end with

 'To get the autoID of the entry we just inserted, do this
 id = db.OpenRecordSet("SELECT@@IDENTITY")(0)
 'Now you have the autoID of the recent insertion, so you may use it for your next one.
于 2012-07-06T13:17:23.207 に答える
1

これは、従来のフォーム/サブフォームのセットアップです。tblrcmtaskサブフォームのみでフォームを作成しますtblrcmtaskoptions。リンクの子フィールドとマスター フィールドは共通 ID に設定する必要があります。ウィザードがこれを行います。コードは必要ありません。ID はリンク フィールドによって自動的に追加されます。

2007 バージョンの Northwind サンプル データベースで例を確認できます。

于 2012-07-06T09:26:47.933 に答える