私はVBAに非常に慣れていません。ベクトルの中央値を計算しようとしました。次のコードは、「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