我有一个表单,其中包括一个多选中复选框列表框。该字段从“国家”表中提取值,该表中有一个“当前索引”列,我需要对每个选定的国家进行检查。更新字段后,我希望找到选定国家的最低“当前索引”值,并使用此值填充一个单独的字段“最低腐败指数”。
我已经将下面的VBA代码附加到复选框列表框中,但是当我测试它时,我会得到以下错误。有人能指出我错过了什么吗?我假设这与我如何连接DLookup的标准有关,但在网上找不到任何有用的指导。
Private Sub Countries_AfterUpdate()
Dim currentIndex As Variant 'variable to hold index of current country during iteration
Dim countryID As Variant 'variable for iterating through array
Dim arrCountryIDs() As Variant 'array of country IDs
Dim recCountries As Recordset 'Countries table recordset
Dim bytLowestIndex As Byte 'variable to track lowest corruption index of selected countries
Dim strLookupCriteria As String 'workaround for trying to concatenate variable into DLookup criteria
'assign contents of Countries field to array
arrCountryIDs = Me![Countries].Value
'assign lookup countries table as recordset
Set recCountries = CurrentDb.OpenRecordset("look_countries")
'set lowest index variable to highest possible value
bytLowestIndex = 100
'iterate through country ID array, look up index, compare to and update lowest index variable
For Each countryID In arrCountryIDs
strLookupCriteria = "Country ID = " & countryID
currentIndex = DLookup("Current Index", "recCountries", strLookupCriteria)
If currentIndex < bytLowestIndex Then bytLowestIndex = currentIndex
Next countryID
'populate lowest corruption index field
Me![Lowest Corruption Index] = bytLowestIndex
'close recordset and empty all variable
recCountries.Close
Erase arrCountryIDs
Set recCountries = Nothing
End Sub
更新:万一这对将来的其他人有用,这是我的最后代码.
Private Sub Countries_AfterUpdate()
Dim currentIndex As Variant 'variable to hold index of current country during iteration
Dim countryID As Variant 'variable for iterating through array
Dim arrCountryIDs() As Variant 'array of country IDs
Dim bytLowestIndex As Byte 'variable to track lowest corruption index of selected countries
'assign contents of Countries field to array
arrCountryIDs = Me![Countries].Value
'set lowest index variable to highest possible value
bytLowestIndex = 100
'iterate through country ID array
For Each countryID In arrCountryIDs
'look up index for this country
currentIndex = DLookup("[Current Index]", "look_countries", "[Country ID] = " & countryID)
'update the lowest index variable if this value is lower
If currentIndex < bytLowestIndex Then bytLowestIndex = currentIndex
Next countryID
'populate lowest corruption index field
Me![Lowest Corruption Index] = bytLowestIndex
'clear the array
Erase arrCountryIDs
End Sub
发布于 2017-03-27 09:58:42
在字段名中使用空格,因此:
strLookupCriteria = "[Country ID] = " & countryID
currentIndex = DLookup("[Current Index]", "recCountries", strLookupCriteria)
https://stackoverflow.com/questions/43043011
复制相似问题