所以我在这里有一个显示棒球运动员姓名,薪水的查询,然后显示正常的棒球统计数据,如命中,打点等。我想要的是让代码在最后创建一个查询包含播放器的名称和表达式
的结果 IIf([H]<>0,Format(([Salary]/[H]),'$#,###.##'),0) AS Per_H
我基本上希望能够在名字和工资之后将该公式应用于每一列。
现在我有
Table PlayerSal
NAME SALARY H R HR
H为Hits,R为Runs,HR为Homeruns。 我想要的结果查询应该是这样的。
Player_Per
NAME Per_H, Per_R, Per_HR.
我到底需要做什么?
修改
我应该补充一下,是的,我知道我可以为每个我想要计算的数据输入相同的函数,这不是重点。我正在尝试扩展我的知识,同时将它应用于我感兴趣的东西。但是,我知道这可能会扩展到其他方面。
答案 0 :(得分:1)
Public Function HitTest()
Dim db As Database
Dim rec As DAO.Recordset
Dim fld As DAO.Field
Set db = CurrentDb
Set rec = db.OpenRecordset("tblPlayers")
EditTable = "tblPlayers"
For Each fld In rec.Fields
If fld.Name <> "PName" And fld.Name <> "Salary" And Left(fld.Name, 4) <> "Per_" Then
strFieldName = "Per_" & fld.Name & ""
'rs.Fields (strFieldName)
'X = "IIf(rec([" & fld.Name & "]) <> 0, Format((rec([Salary]) / rec([" & fld.Name & "])), '$#,###.##'), 0)"
If FieldExists(EditTable, strFieldName) Then
Else
'AltTable = "ALTER TABLE " & EditTable & " ADD COLUMN " & strFieldName & " Double;"
'CurrentDb.Execute (AltTable)
End If
rec.Edit
X = IIf(rec((fld.Name)) <> 0, Format((rec("Salary") / rec((fld.Name))), "$#,###.##"), 0)
rec.Fields(strFieldName).Value = X
rec.Update
End If
Next fld
End Function
答案 1 :(得分:0)
我确定我不理解这个问题,但你可以这样做:
Dim db as database
dim rec as recordset
Dim fld as Field
Set db = CurrentDB
Set rec = db.OpenRecordset("PlayerSal")
For each Fld.name in rec
If Fld.Name <> "Name" and Fld.Name <> "Salary" then
Per_" & Fld.Name & " = IIf([" & Fld.Name & "]<>0,Format(([Salary]/[" & Fld.Name & "]),'$#,###.##'),0)
End If
Next Fld.Name
以上是完全“空气码”,很可能不会开箱即用,但希望它能给你一个想法。
答案 2 :(得分:0)
我对此做了一些研究。看起来您需要打开记录集以确保所有“Per_”字段都存在并确定您需要添加的任何新字段。然后,您需要关闭记录集并运行ALTER TABLE语句以创建所需的任何新字段。然后,您需要重新打开记录集并使用公式的值更新字段。
如果您只是手动添加新字段,则可以取消前两个步骤,但这就是您必须这样做的方法。如果你想消除前两个步骤,你最终会得到这样的结果:
Dim db As Database
Dim rec As DAO.Recordset
Dim fld As DAO.Field
Set db = CurrentDb
Set rec = db.OpenRecordset("tblPlayers")
EditTable = "tblPlayers"
For Each fld In rec.Fields
If fld.Name <> "PName" And fld.Name <> "Salary" Then
strFieldName = "Per_" & fld.Name & ""
X = "IIf([" & fld.Name & "] <> 0, Format(([Salary] / [" & fld.Name & "]), '$#,###.##'), 0)"
If FieldExists(EditTable, strFieldName) Then
rec.Edit
rec.Fields(strFieldName).Value = X
rec.Update
Else
End If
End If
Next fld
然后你需要这个函数来检查该字段是否存在:
Public Function FieldExists(ByVal tableName As String, ByVal fieldName As String) As Boolean
Dim nLen As Long
On Error GoTo Failed
With DBEngine(0)(0).TableDefs(tableName)
.Fields.Refresh
nLen = Len(.Fields(fieldName).Name)
If nFldLen > 0 Then FieldExists = True
End With
Exit Function
Failed:
If Err.Number = 3265 Then Err.Clear ' Error 3265 : Item not found in this collection.
FieldExists = False
End Function