charles_m80
charles_m80

Reputation: 63

Access vba pass variable into code

I'm in Access 07 trying to pass a variable to a line of code. The purpose is to make an array of field names and then loop over the array performing the same action on each field. I've simplified it down to avoid any potential problems with the array or the loop. In any other language I am familiar with it would be pretty simple, but I can't seem to format it in VB.

Me.FeildName.Locked = True

would be the static code, and I think the variable code would look something like this:

Dim Temp as String
Temp="FieldName"
Me.[Temp].Locked = True

but it keeps giving me an error that says "can't find the field '|' referred to in your expression", so it's not reading the value of the variable.
How do I get it to read the variable in the command?

Alternatively, I've tried to concatenate strings into a line of code:

Dim CodeLine As String
Dim TestName As String
TestName = "FieldName"
CodeLine = "Me.[" & TestName & "].Locked = True"

This creates a string that looks like functional code but how would I run it?

Thanks

Upvotes: 1

Views: 880

Answers (2)

VBlades
VBlades

Reputation: 2251

Dick Kusleika's answer is the way to go, but for completeness' sake, you can do also something like this:

For i = LBound(strControlNames) To UBound(strControlNames)
    CallByName Forms![MyFormName].Controls(strControlNames(i)), "Locked", VbLet, "True"
Next

strControlNames would be the array with your control names.

Upvotes: 0

Dick Kusleika
Dick Kusleika

Reputation: 33175

If Me is a form, you need

Temp = "FieldName"
Me.Controls(Temp).Locked = True

Upvotes: 2

Related Questions