Can you use a variable for the Field name when using AddNew to a record set?

Sinister Beard picture Sinister Beard · Feb 19, 2014 · Viewed 20.4k times · Source

I'm using a DAO recordset to update a table because of problems enocuntered here.

This works fine when I know the name of the field I'm updating, e.g.:

rs2.AddNew
rs2![ContactID] = rs.Fields(0).Value
rs2![Fee Protection Insurance] = "" & strValue & ""
rs2.Update

works perfectly.

However, the field that I'm trying to update won't always have the same name, so I attempted to use a variable here too, expecting it to evaluate and be equivilent to the above code:

rs2.AddNew
rs2![ContactID] = rs.Fields(0).Value
rs2!["strFieldName"] = "" & strValue & ""
rs2.Update

but it tells me that item's not in the collection, even when strFieldName is set to Fee Protection Insurance.

I've tried this various ways, including:

rs2![" & strFieldName & "] = "" & strValue & ""

rs2![strFieldName] = "" & strValue & ""

rs2!["" & strFieldName & ""] = "" & strValue & ""

rs2![cStr(strFieldName)] = "" & strValue & ""

none of which work.

Am I going about this the wrong way, or am I attempting something impossible?

Answer

Dmitry Pavliv picture Dmitry Pavliv · Feb 19, 2014

Try to use this one:

rs2.Fields(strFieldName) = "" & strValue & ""