我在整个数据库中使用2个函数。我想知道是否可以“合并”两者以“缩短”我的代码。
Option Compare Database
Option Explicit
Dim strTaxR As String
Dim strYTDG As String
Public Function fncTRate(ByVal PEnd As Date) As Double
strTaxR = "SELECT TOP 1 [Tax Rate] As TRate FROM tblTax WHERE [Effective Date] <= #" & PEnd & "#" ORDER BY [Effective Date] DESC;"
With CurrentDb.OpenRecordset(strTaxR)
If Not (.BOF And .EOF) Then
fncTRate = .Fields("TRate")
End If
End With
End Function
Public Function fncYTDG(EmpN As Integer, PEnd As Date) As Double
strYTDG = "SELECT Sum([SGROSS]) As YTDG FROM qryYTD2 WHERE [PE] Between #" & DateSerial(Year(PEnd ), 1, "1") & "# And #" & PEnd & "# And [EID]=" & EmpN
With CurrentDb.OpenRecordset(strYTDG)
If Not (.BOF And .EOF) Then
fncYTDG = .Fields("YTDG")
End If
End With
End Function
压缩它会有所不同还是应该保留原样?
您可以这样做:
Public Function fncGrossRate( _
ByVal GrossOrRate As Integer, _
ByVal PEnd As Date, _
Optional ByVal EmpN As Integer) _
As Currency
Dim SQL As String
Dim Result As Currency
Select Case GrossOrRate
Case 0
SQL = "SELECT TOP 1 [Tax Rate] As TRate FROM tblTax " & _
"WHERE [Effective Date] <= #" & Format(PEnd, "yyyy\/mm\/dd") & "# ORDER BY [Effective Date] DESC;"
Case 1
SQL = "SELECT Sum([SGROSS]) As YTDG FROM qryYTD2 " & _
"WHERE [PE] Between #" & Format(DateSerial(Year(PEnd), 1, 1), "yyyy\/mm\/dd") & "# And #" & Format(PEnd, "yyyy\/mm\/dd") & "# And [EID]=" & EmpN & ""
End Select
If SQL <> "" Then
With CurrentDb.OpenRecordset(SQL)
If Not (.BOF And .EOF) Then
Result = .Fields(0).Value
End If
End With
End If
fncGrossRate = Result
End Function
但是,正如[[June所说,对您问题的直接答案是No。