Access VBA中使用SQL的For循环问题

问题描述

我正在处理一个员工数据库,其中有一个培训表格。我有 2000 多名员工不时需要培训。我需要以这种形式创建一批预定数量(即 50)的员工。此外,我需要为每次新​​培训创建它们。因此,培训与 TrainingID 相关联。我创建了一个 for 循环语句,如下所示:

Dim StartC As Integer
Dim EndC As Integer

Set StartC = Nz(DMax("BatchNo","T25TrnBatch","T25TrnBatch.TrnID= " & Forms!F13NewTraining!TrnId),0) + 1
Set EndC = Me.TBatchtxt

Strsql = "INSERT INTO T25TrnBatch(TrnID,BatchNo) VALUES((Forms!F13NewTraining!TrnId),StartC);"

For BCounter = StartC To EndC
    DoCmd.SetWarnings False
    DoCmd.Runsql Strsql
    DoCmd.SetWarnings True
Next BCounter

(注:TBatchtxt 是需要创建的总批次数

但是当我运行它时会弹出一个说 StartC。

我还希望结果如下:

BatchNo TrnID

1 101

2 101

3 101

请帮助。 谢谢。

解决方法

您正在执行的 SQL 语句不“知道”您要插入的值 - 您必须将这些值连接到 SQL 字符串中。作为调试的提示,您可以在将值连接起来后在行上放置一个 Debug.Print StrSQL 以查看它的实际情况。

另外,SQL 语句不在循环内,所以值永远不会改变。相反,无需在循环内更改 SetWarnings - 您只需在循环外更改即可。

Dim StartC As Integer
Dim EndC As Integer

Set StartC = Nz(DMax("BatchNo","T25TrnBatch","T25TrnBatch.TrnID= " & Forms!F13NewTraining!TrnId),0) + 1
Set EndC = Me.TBatchtxt


DoCmd.SetWarnings False
For BCounter = StartC To EndC
    StrSQL = "INSERT INTO T25TrnBatch(TrnID,BatchNo) " _   
        & " VALUES(" & Forms!F13NewTraining!TrnId & "," & BCounter & ");"
    DoCmd.RunSQL StrSQL
Next BCounter
DoCmd.SetWarnings True

问候,

,

好的,我已经想通了。我在 SQL 中再次插入了 DMax 函数。如下:

Dim BCounter As Integer '''I forgot to mention this line in my question
Dim StartC As Integer
Dim EndC As Integer

StartC = Nz(DMax("BatchNo",0) + 1
EndC = Me.TBatchtxt


DoCmd.SetWarnings False
For BCounter = StartC To EndC
StrSQL = "INSERT INTO Table1Test(TID,BID) " _
    & " VALUES(" & Forms!TestForm1!TIDtxt & "," & Nz(DMax("BatchNo",0) + 1 & ");"
DoCmd.RunSQL StrSQL
Next BCounter
DoCmd.SetWarnings True

感谢@Applecore 为我指明了正确的方向。