Call constant using literals in runtime - excel

I have declared constants like the below in the module,
Public Const strFolderA1 = "C:\ABCD\One"
Public Const strFolderA2 = "C:\ABCD\two"
I am trying to call this in a loop,
For i = 1 To 3
strFile = Dir(strFolderA & i & "\" & filenm)
Loop
The above Dir code is wrong, but I want to call the constant based on the looping integer.
Could someone help?
Please let me know if the question is not clear.

VBA does not provide any method for concatenating a string to be used as a dynamic variable name. You could create a string constant with a delimiter then split it before use.
Option Explicit
Public Const strFolderA As String = "C:\ABCD\One|C:\ABCD\Two|C:\ABCD\Three"
Sub abcs()
Dim i As Long, fldrs As Variant
fldrs = Split(strFolderA, "|")
For i = LBound(fldrs) To UBound(fldrs)
Debug.Print fldrs(i)
Next i
End Sub

Related

Formatting Inputs with Rules in VBA

not sure how do phrase this question but I really dont understand it.
I want to achieve the following:
TextBox = TextVorname
TextBox = TextNachname
For Example I put in the 1. Textbox "Markus"
and put in the 2. Textbox "Neumann"
I want it to display in the Bookmark "Ma.Ne_2022"
I have following Code:
Private Sub OptionButton1_Click()
Dim VornameStr As String
VornameStr = Me.TextVorname.Caption
Dim NachnameStr As String
NachnameStr = Me.TextNachname.Caption
MyStrVorname = Left(VornameStr, 2)
MyStrNachname = Left(NachnameStr, 2)
MyStrFullname = MyStrVorname & "." & MyStrNachname & "_2022"
Call UpdateBookmark("test1", Me.MyStrFullname.Caption)
End Sub
Your question is a little bit vague.. Maybe this is what you're after?
Dim MyVornameStr As String
Dim MyNachnameStr As String
Dim MyStrFullname As String
MyStrVorname = Left(Me.TextVorName.Text, 2)
MyStrNachname = Left(Me.TextNachName.Text, 2)
MyStrFullname = MyStrVorname & "." & MyStrNachname & "_2022"
Call UpdateBookmark("test1", MyStrFullname)

Use a variable to refer to other variables?

So my macro uses many string constants to store the filenames of workbooks I want to edit. Each variable uses the naming convention template and then a 3 digit number (e.g. template001). Is there a way I can use an integer variable to refer to which constant I want to use? I'm imagining something like this:
Public Const filepath = "C:\Templates\"
Public Const template001 = "001.xls"
Sub printTemplate()
Dim num As Integer: num = 001
Dim template As Workbook
Set template = Workbooks.Open(filepath & GetVar("template" & num)) 'Complete guess at what the function is called
template.PrintOut
template.Close False
End Sub
Is there any such function that does this?

Set variable that is constant for all Subs

I have several Sub's in my Module. I would like to set variable that I can use in all Subs below. How to do that?
Let's say variable is a text from ThisWorkbook.Worksheets("Sheet1").Range("E1").Value and its name should be FileNameINVREQ
How to implement that in the code? I have tried:
Option Explicit
Const FileNameINVREQ As String = ThisWorkbook.Worksheets("Sheet1").Range("E1").Value
Private Sub CreateNewINVREQtoMFiles()
...
' PD Name Or title.
oPVNew.PropertyDef = 0
oPVNew.TypedValue.SetValue MFDatatypeText, FileNameINVREQ
oPVsNew.Add -1, oPVNew
...
End Sub
Private Sub CreateINVREQtoMFiles()
...
oFile.SourceFilePath = Environ("Temp") & "\" & FileNameINVREQ & ".docx"
oFile.Title = FileNameINVREQ
oFile.extension = "docx"
oFiles.Add 0, oFile
...
End Sub
A constant means it cannot be changed. For a variable, taking data from a cell, accessible from everywhere a public function without arguments would do the job:
Public Function FileNameINVREQ() As Variant
FileNameINVREQ = ThisWorkbook.Worksheets("Sheet1").Range("E1").Value
End Function
Pulling a value from a worksheet is technically not a constant (since the value could change) so you'll need to use a variable instead. However, while you can declare variables as global, you can't set them outside of a sub or function.
My suggestion would be to move both the declaration and setting the value to its own subroutine that you reference when you need to know the value.
Global FileNameINVREQ as string
Sub FileName()
FileNameINVREQ = ThisWorkbook.Worksheets("Sheet1").Range("E1").Value
End Sub
Going a step further, you could scrap it as a variable entirely and just change that FileName sub to a function! Hopefully one of these solutions works for you!

How to access the value of a string when defining within a loop

I would like to access the value of a string when declaring new variables so that I can declare new variables within a loop.
I have tried val(), creating a function. An simplified version of my problem can be found in the code below.
Function StudentValue(x As String) As String
StudentValue = x
End Function
Public Sub TEST()
Dim i As Integer
Dim strName As String
Dim n As Integer
n = 20
For i = 1 To n
strName = "Variable" & CStr(i)
'The problem occurs with the next two lines,
'once active they create a string with the name 'strName' and not the
'value of the string eg 'Variable1', 'Variable2', ect
'Attempt1
'Dim strName As String
'Attempt2
'Dim NameFunction(strName) As String
Next i
End Sub
The errors are as follows:
Dim strName As String results in "compile error: Duplicate declaration in current scope"
Dim NameFunction(strName) As String results in "compile error: Constant expression required"
Is there a function that allows you to access the value of a string when declaring variables?
Thank you in advance!
You are getting "Duplicate declaration" Error because you are trying to declare a variable by the same name.
You are getting the error "Constant expression required" Error because Dim XYZ() as string is the syntax for declaring an array. And the value inside the brackets specifies the size of the array and must be constant.
Here is a link on how to use arrays.
Use Option Explicit, it will help you solve problems before they are problems.
Here is your code using arrays.
Option Explicit
Function StudentValue(x As String) As String
StudentValue = CStr(x)
End Function
Public Sub TEST()
Const MaxNumNames As Integer = 20
Dim i As Integer
Dim strNames(1 To MaxNumNames) As String
For i = 1 To MaxNumNames
'This will populate the array of names
strNames(i) = "Variable" & CStr(i)
'To use the name in the loop
Debug.Print "In Loop:" & strNames(i)
Next i
'To use the name outside the loop (Show 5th name)
Debug.Print "Outside Loop: " & strNames(5)
' To use the name in your function outside the loop (Using 2nd Name)
Debug.Print "Using Function: " & StudentValue(strNames(2))
End Sub

read constant from a cell

I am writing a VBA code to read some text files, I would like the file names to be read directly from cells in excel.
I used the following code
Sub ImportFile()
Const textFilePath As String = "C:\Desktop\"
Const textFileName As String = "File1.txt"
Const newTextFileName As String = "NewFile1.txt"
I want to have something like
Sub ImportFile()
Const textFilePath As String = Range("A2").value
Const textFileName As String = Range("A3").value
Const newTextFileName As String = Range("A4").value
I tried different combinations but it does not seem to like the idea of assigning a constant to a cell value, any work around?
Thanks
P.S I don't know how to write the code in a correct way in this website, I tried to add 4 spaces before the code lines but did not seem to work, any idea why?
I don't think you can assign a constant from a range because the range value could change during your code execution. I tried your declarations in this bit of code:
Option Explicit
Sub ImportFile()
Const textFilePath As String = Range("A2").Value
Const textFileName As String = Range("A3").Value
Const newTextFileName As String = Range("A4").Value
End Sub
and on Debug..Compile in the IDE I got this error
If you change your code to
Option Explicit
Sub ImportFile()
Dim textFilePath As String
Dim textFileName As String
Dim newTextFileName As String
textFilePath = Range("A2").Value
textFileName = Range("A3").Value
newTextFileName = Range("A4").Value
End Sub
You'll find it compiles OK.
Unless you're talking "Universal (physical) constants" like PI,c or G for example, constants rarely are constant. I've found that having a named range, possibly on a hidden sheet, and populating a variable from that named range makes for easier maintenance by users with little no VBA experience. Sure, you need to keep track of those "constants" to maintain them but at least you don't need VBA experience to do so.
You can't do that in vba since your constant variables might change. However, I think that you want to declare and initialize your path variables once so that later if you decide to change them you can do that in one place in the same row where the variable was initialized. So If I were you I would use something like
Option Explicit
sub macro()
Dim FILEPATH As String: FILEPATH = Range("A1").Value
MsgBox FILEPATH
end sub

Resources