我对 VBA 很陌生。我试图计算向量的中位数。以下代码不断收到有关“Block if without End if”的警告。我试图更改“End IF”的位置,但它导致另一个警告“Block end if without if”。您的意见将不胜感激。谢谢。
Sub CalculateMedian()
DoCmd.SetWarnings False
Dim db As DAO.Database
Dim onet As DAO.Recordset
Dim Ocode As String
Dim ag As DAO.Recordset
Dim agMedian As Integer
Set db = CurrentDb
'select one variable in current database
Set onet = db.OpenRecordset("SELECT DISTINCT ONetCode FROM Single WHERE LEN(ONetCode)>8")
Do While Not onet.EOF
'assigning value to a variable does not need a "SET"
Ocode = onet.Fields("ONetCode")
'any data meet the criterion--&Ocode& can vary
Set ag = db.OpenRecordset("SELECT AG FROM Single WHERE ONetCode='" & Ocode & "' ORDER BY AG")
'using .recordcount needs to use .movelast first
ag.MoveLast
ag.MoveFirst
If ag.RecordCount Mod 2 = 1 Then
agMedian = ((ag.RecordCount + 1) / 2)
thecount = 0
Do While Not ag.EOF
thecount = thecount + 1
If thecount = agMedian Then
'inset the result into a new table, and need to create a new table in advance
DoCmd.RunSQL ("INSERT INTO PCImedian(onetcode, agMedian) VALUES('" & Ocode & "'," & ag("AG") & ");")
Exit Do
End If
If ag.RecordCount Mod 2 = 0 Then
agMedian = ag.RecordCount / 2
thecount = 0
Do While Not ag.EOF
thecount = thecount + 1
If thecount = agMedian Then
m1 = ag("AG")
ElseIf thecount = agMedian + 1 Then
m2 = ag("AG")
DoCmd.RunSQL ("INSERT INTO PCImedian(onetcode, agMedian) VALUES('" & Ocode & "'," & ((m1 + m2) / 2) & ");")
Exit Do
End If
Loop
DoCmd.SetWarnings True
End Sub