vba 在对记录集使用 AddNew 时,您可以为字段名称使用变量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21885101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you use a variable for the Field name when using AddNew to a record set?
提问by Sinister Beard
I'm using a DAO recordset to update a table because of problems enocuntered here.
由于这里遇到的问题,我正在使用 DAO 记录集来更新表。
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.
但它告诉我该项目不在集合中,即使 strFieldName 设置为费用保护保险也是如此。
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?
我是在以错误的方式解决这个问题,还是我在尝试不可能的事情?
回答by Dmitry Pavliv
Try to use this one:
尝试使用这个:
rs2.Fields(strFieldName) = "" & strValue & ""
回答by Jay
Very Simple answer YES you can access VARIABLE FIELD NAMES. For example: I have a form that has multiple buttons... Here's how to name and access them.
非常简单的答案是的,您可以访问变量字段名称。例如:我有一个包含多个按钮的表单...这是命名和访问它们的方法。
Name each Button on your form: MyButton(1) through MyButton(X) The code places the number on each button by changing the caption. stButton is the string value of the Button name
为表单上的每个按钮命名:MyButton(1) 到 MyButton(X) 该代码通过更改标题将数字放置在每个按钮上。stButton 是按钮名称的字符串值
X=10
X=10
For Btn = 1 To X
对于 Btn = 1 到 X
Set StButton = Me("MyButton" & "(" & Btn & ")")
Set StButton = Me("MyButton" & "(" & Btn & ")")
StButton.Caption = Btn
StButton.Caption = Btn
Next Btn
下一个