我有一个包含多选复选框列表框的表单。此字段从“国家/地区”表中提取值,该表具有“当前索引”列,我需要为所选的每个国家/地区检查该列。在更新字段后,我想找到所选国家/地区的最低“当前指数”值,并使用此值填充单独的字段“最低腐败指数”。
我已将以下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
答案 0 :(得分:1)
您在字段名称中使用空格,因此:
strLookupCriteria = "[Country ID] = " & countryID
currentIndex = DLookup("[Current Index]", "recCountries", strLookupCriteria)