Is there anyway to use variables in text fields? - vba

Is there anyway to use variables in text fields?
For example i have a variable for my file directory STRDIR and default setted to workbooth path
Is there any way to user can write to textbox(name TextBox1) in VBA like that {STRDIR}/theirfilename.txt and after that i plan to see when i Debug.Print TextBox1.Value i would like to see result as STRDIR + "theirfilename.txt"
Is it possible to use like that ? Regards.

You can use
Debug.Print Replace(Textbox1.Value, "{STRDIR}", STRDIR)
but there's no automatic process for variable substitution

Use & for concatenating strings and string-variables.
+ sometimes works with strings in VBA but should be reserved for addition.
Unless you literally want to display the name of the variable, like your example:
`STRDIR + "theirfilename.txt"`
..which means you're looking for a function to provide the same output as this:
Debug.Print "STRDIR + ""theirfilename.txt"""
...but I doubt that's what you mean.

Related

Access 2016 Subform VBA Using Double Constant as Object?

So I have a subform VBA function that looks like this:
Function GetVariable() As Double
' <control> = DLookup("<table var>","<table>", "<other table var> = <control>"
[someFunction] = DLookup("[Var]", "[tblExample]", "[tblExampleVar] = [subFormControl]")
' (return) = ( <control> - <otherControl>) / 12345.12
GetVariable = ([finalPosition] - [someFunction]) / 12345.12
End Function
And when I open the parent form (the form that contains this subform), I get the error, "Run-time error '2447' There is an invalid use of the . (dot) or ! operator or invalid parentheses."
What I gather from this is that Access is interpreting 12345.12 as an object and I do not understand why. When I run this subform on its own it works, but when it is a subform it does not. Has anyone dealt with this before?
Extra information: I have two subforms in this parent form that use the same calculation, both repeated in their form-specific VBA, and I do not think that they would conflict with one another because they do not share scope. So my conclusion remains that Access is trying to use 12345.12 as (object).member.
Thanks for reading.
Try to take care of Null values and to be more specific.
Also, a decimal value must be concatenated as a string with dot decimal separator:
Function GetVariable() As Double
If Not IsNull(Me![subFormControl].Value) Then
Me![someFunction].Value = DLookup("[Var]", "[tblExample]", "[tblExampleVar] = " & Str(Me![subFormControl].Value) & "")
If Not IsNull(Me![finalPosition].Value - Me![someFunction].Value) Then
GetVariable = (Me![finalPosition].Value - Me![someFunction].Value) / 12345.12#
End If
End If
End Function
References that work when a form opens independent won't necessarily work when that same form is used as a subform. That requires referencing to include the subform container name.
I don't see how running form as standalone could return correct data. I presume [subFormControl] is a field or control on form. This is a variable input. Variable must be concatenated in the DLookup() WHERE condition expression.
It seems these fields return names of controls or table. Do these names have spaces or punctuation/special characters (other than underscore). Really should not use in names nor use reserved words as names. If you do, need to delimit with [].
If you are referencing fields/controls on form to build a DLookup(), then all the inputs are variables and should be concatenated.
[someFunction] = DLookup("[" & [Var] & "]", "[" & [Table] & "]", "[" & [Condition] & "] = '" & [subformControl] & "'")
Whether or not delimiters are needed (and which ones) depends on the field type of the field that will be returned by the Condition input in the filter criteria.

How to remove part of a string backwards?

I have a vb string with this value: c:\program\bin\files
I need to convert this string to this value: files
All i need is the last folder of the path.
The path is not fixed. It can be anything like: d:\app\win\7\sp1\update
In this case the string must be converted to: update
I think that should be done by searching the string backwards for the first occurrence of \ and removing everything before it, including the \ itself.
But obviously i don't know how to do it. :)
Thank you!
EDIT:
I need to use this to fill a ComboBox...
This is what i am using:
ComboBox1.Items.AddRange(IO.Directory.GetDirectories(appPath & "\Updates\Version"))
It gives me a ComboBox like:
c:/program/Updates/Version/Beta1
c:/program/Updates/Version/Beta2
c:/program/Updates/Version/Beta3
c:/program/Updates/Version/Beta4
And i would like to have the ComboBox like:
Beta1
Beta2
Beta3
Beta4
Rather than try to pull apart the string yourself, have a look at the System.IO.Path class.
In your case, the GetFileName method does what you want:
lastFolder = System.IO.Path.GetFileName(path)
To fill a combo box with names you can use a LINQ query like this:
ComboBox1.Items.AddRange(
From path
In IO.Directory.GetDirectories(IO.Path.Combine(appPath, "Updates\Version"))
Select IO.Path.GetFileName(path))
Also, try to use the Path.Combine method when joining path fragments together. It's safer than just joining strings.
In VBScript, which this is tagged you have two choices. This was written before any code was edited into the question.
Use InstrR which is Instr but from back to front of string.
You also have StrReverse which reverses a string.
InStrRev
Returns the position of an occurrence of one string within another, from the end of string.
InStrRev(string1, string2[, start[, compare]])
StrReverse
Returns a string in which the character order of a specified string is reversed.
StrReverse(string1)
If using the File System Object it has a method to do specifically what you want.
GetParentFolderName Method
Returns a string containing the name of the parent folder of the last component in a specified path.
Set fso = CreateObject("Scripting.FileSystemObject")
object.GetParentFolderName(path)

Foreign letters ÅÄÖ hve been replaced by other characters in my VBA-code. Both strings and range names have been affected. Why?

Foreign letters ÅÄÖ hve been replaced by other characters in my VBA-code. Both strings and range names have been affected. This has happened after I have sent the file to a client.
Obviously I could change the names of variables to not contain ÅÄÖ, although that would be somewhat tedious. But references to worksheets and other things that affect the user interface have also been messed up. Why has this happened? Can I stop it from happening?
Examples before:
MsgBox ("Ett oförutsätt fel har skett.")
Range("ActionsColumnAffärsläget")
Examples after:
MsgBox ("Ett ofšrutsŠtt fel har skett.")
Range("ActionsColumnAffŠrslŠget")
Instead of typing the characters directly you can replace them by referencing their character code in your message box string like so...
MsgBox("Ett of" + Chr(246) + "ruts" + Chr(228) + "tt")
It's stupidly verbose way of doing it but should work.
To avoid typing out Chr(###) everytime you need them you can put the characters you need in a short form variable like...
Dim a As String = Chr(228)
Dim o As String = Chr(246)
MsgBox("Ett of" + o + "ruts" + a + "tt")
Although I find Zack's solution much more elegant than mine (finally, you should type the code only once), here is a work around that will avoid you to write the code as a composition of characters:
Place your sentence in the range (for example) "A1" of the worksheet "Dictionary" that you will create;
Write in Range("A1") the value Ett oförutsätt fel har skett.
Change your code with MsgBox(Sheets("Dictionary").Range("A1")
Unfortunately there's no way to embedd special characters into the source code, you will need either one or the other work around (usually these are contained in XML files).

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
If Me is a form, you need
Temp = "FieldName"
Me.Controls(Temp).Locked = True
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.

Escaping text so it would remain readable

I have a method which looks like this
def full
"#{self.first} #{self.second}"
end
problem is that I want to escape it, so to do it in the model I do
def full
ERB::Util.h("#{self.first} #{self.second}")
end
but if first or second have & in it, it would give me & instead of &
also if they have apostrphies ' it would escape them and make it unreadable..
Is there a way to avoid XSS and make the string readable as well?
I think you can use this html_escape Click here...