在页面顶部,在我声明任何函数或子例程之前,我声明了一个公共变量i。 在子例程addRow()和removeRow()中,他们可以毫无问题地访问i,但是当我尝试在函数generateIf(s As String,x As Integer)中访问它时,它表示它已脱离上下文。为什么会这样,我该如何解决?
Option Compare Database
Public i As Integer
Private Sub buttonSubmit_Click()
sql = generateSQL()
End Sub
Private Sub Form_Load()
i = 0
End Sub
Private Sub buttonCancel0_Click()
removeRow
End Sub
Private Sub buttonAdd0_Click()
addRow
End Sub
Private Sub addRow()
Dim f As Form
DoCmd.OpenForm "Create_Report"
Set f = Forms!Create_Report
If i = 4 Then
GoTo LastLine
End If
i = i + 1
'Sets next row visible
f.Controls("cmbNum" & CStr(i)).Visible = True
f.Controls("cmbMetric" & CStr(i)).Visible = True
f.Controls("cmbCond" & CStr(i)).Visible = True
LastLine:
End Sub
Private Sub removeRow()
Dim f As Form
DoCmd.OpenForm "Create_Report"
Set f = Forms!Create_Report
'Sets next row visible
If i = 0 Then
GoTo LastLine
End If
f.Controls("cmbNum" & CStr(i)).Visible = False
f.Controls("cmbMetric" & CStr(i)).Visible = False
f.Controls("cmbCond" & CStr(i)).Visible = False
i = i - 1
LastLine:
End Sub
Public Function generateSQL() As String
Dim sql, transform, sel, from, where, groupBy, oderBy, pivot, ifStatement As String
transform = "TRANSFORM Count([9_0_result_data].[Current Proposal Status]) AS Expr2"
from = "FROM 9_0_result_data"
where = "WHERE ((([9_0_result_data].DayDiff)>=0) AND (([9_0_result_data].[Current Proposal Status])='Funded'))"
ifStatement = generateIf("", 0, i)
sel = ""
End Function
Public Function generateIf(s As String, x As Integer) As String
Dim sql As String
sql = s
Dim f As Form
DoCmd.OpenForm "Create_Report"
Set f = Forms!Create_Report
sql = sql & "IIf(DateDiff('" & LCase(Left$(f.Controls("cmbMetric" & CStr(x)).Value, 1)) & "',[" & cmbCompare0.Value & "],[" & cmbCompare1.Value _
& "])" & f.Controls("cmbCond" & CStr(x)).Value & f.Controls("cmbNum" & CStr(x)).Value & ",'" _
& f.Controls("cmbNum" & CStr(x)).Value & f.Controls("cmbMetric" & CStr(x)).Value & "',"
x = x + 1
If x >= i Then
sql = sql & "'" & f.Controls("cmbMetric" & CStr(x)).Value & f.Controls("cmbNum" & CStr(x)).Value & "'"
Else
sql = generateIf(sql, x)
End If
sql = sql & ")"
'Stupid VBA return values
generateIf = sql
End Function