Use comma separated string as function parameters - string

I have created a comma separated string. I want to use this string as input in an Application.Run procedure.
The string looks exactly like below - with quotes..
MyString = "First_Number", "Second_Number", "Third_Number"
I want to use this string as parameter input:
Application.Run("'" & "Book2.xlsm" & "'!MySub", *MyString*)
It doesn't work.. I get an "argument not optimal".
I build the string with the following code, and the range is just a row with the parameters.
Function csvRange(myRange As Range)
Dim csvRangeOutput
For Each entry In myRange
csvRangeOutput = csvRangeOutput & entry.Value & """, " & """"
Next
csvRange = Left(csvRangeOutput, Len(csvRangeOutput) - 4)
End Function
Hope someone can help.

Evaluate might do the trick. Look at this piece of test-code:
Sub Test()
Dim params As String
params = "3,5"
Debug.Print Evaluate("addNumbers(" & params & ")")
End Sub
Function addNumbers(a As Integer, b As Integer) As Integer
addNumbers = a + b
End Function
It's code that writes code, how exiting! :D

maybe you can use something like this.
String MyString = "First_Number, Second_Number, Third_Number";
String words[] = MyString.split(",");
Then use the individual words as words[0],words[1], etc.
or you can loop through the array words[] and use the individual terms as you like.

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)

Excel output value based on multiple strings in cell [duplicate]

I want to find if a string contains a ","(comma) in it. Do we have any other option other than reading char-by-char?
Use the Instr function (old version of MSDN doc found here)
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
will return 15 in pos
If not found it will return 0
If you need to find the comma with an excel formula you can use the =FIND(",";A1) function.
Notice that if you want to use Instr to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare (or just 1 for die-hards).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
will give you a value of 14.
Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.
You can also use the special word like:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.
Per #rene's answer...
Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
...would return 20 to pos, instead of 6.
Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:
Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function
You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA
Option Explicit
Public Sub test()
Debug.Print ContainsSubString("bc", "abc,d")
End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
'substring = string to test for; testString = string to search
ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")
End Function

VBA behaving weirdly, can't get the value stored in variable

I am having a very strange problem. I am not able to get the value returned from a simple function as below if the return value is more than one char. Now the second problem is that following code is not assigning "WTH" to sheetName variable. Refer to the screenshot 2. UPDATED AFTER CYRIL'S COMMENTS
Public Sub WTHFormatter()
Dim sheetName As String
sheetName = "WTH"
Dim rng1 As Range
'delete empty rows
lastRowWTH = getLastRow(sheetName, 2)
'Delete rows below the last Row
Worksheets(sheetName).Rows(lastRowWTH + 1 & ":" & Worksheets(sheetName).Rows.Count).Delete
' build first range
Set rng1 = Worksheets(sheetName).Range("B11:F" & lastRowWTH)
Call setCellBorders(rng1)
Set rng1 = Worksheets(sheetName).Range("H11:K" & lastRowWTH)
Call setCellBorders(rng1)
'determine the range for months
For i = 13 To 24
If Cells(7, i) = "" Then
lastCol = i - 1
Exit For
End If
lastCol = i
Next
ColLetter = returnLabel(lastCol)
ColLetter2 = returnLabel(lastCol + 2)
ColLetterX = returnLabel(lastCol + 14)
Set rng1 = Worksheets(sheetName).Range("K17:" & ColLetter & lastRowWTH)
Call setCellBorders(rng1)
Set rng1 = Worksheets(sheetName).Range(ColLetter2 & lastRowWTH & ":" & ColLetter3 & lastRowWTH)
Call setCellBorders(rng1)
End Sub
Function returnLabel(num1 As Long) As String
Dim ColumnLetter As String
ColumnLetter = Split(Cells(1, num1).Address, "$")(1)
returnLabel = ColumnLetter
End Function
The above function returns blank and varTest has nothing after the execution. If I do the line by line execution, I see that test1 in function is not 'Null'.
If I break the execution and probe the variables I see "test1 =" only as per the screen shot below. And this is breaking my code.
Strangely, If I call the function from 'Immediate Window', it returns the expected value.
Things I have already done:
I have tested in a fresh file using simple code as above.
Tested in different PC and the same code is working fine with same version of Windows 10 & Office 365.
Updated / Re-installed MS Office 365
Restarted the PC
If the return value is a single character like "A", the code is working fine.
Failed to understand the reason here. Any help is appreciated.
UPDATE1
I tried it on a fresh file while the code above worked, but the main code is having a new similar problem. This has started happening just now. It's not assigning a string value to the variable. See the attached screenshot.Screenshot of the VBA Code. I am assuming there is some problem with system or some virus.
If the idea is to have a function, that an array, this is possible with the following code:
Function Test1() As Variant
ReDim result(2)
result(0) = "AJ"
result(1) = "A"
Test1 = result
End Function
Sub Main()
Dim varTest As Variant
varTest = Test1(0)
Debug.Print varTest
varTest = Test1(1)
Debug.Print varTest
End Sub
It is questionable why would it be needed, but as a "test-exercise" it is ok.
Going to put my comments into an answer to consolidate and add more explanation.
Pointing out some errors in the code before correcting:
Function test1(num1) 'declare `as variant` to ensure you're returning an array
test1 = "AJ" 'this appears to be saving a single string to var test1
test1 = "A" 'you are now overwriting the above string
End function
Sub test()
varTest = test1(1) 'you have a single string from the function and arrays start at 0, not 1
End sub
You would want to specify the place in the array, after declaring an array, within your function such that:
Function test1() As Variant
Dim arr(2) As Variant 'added array because test1 = BLAH is the final output in a function
arr(0) = "AJ" 'added (1) to call location in array
arr(1) = "A" 'added (2) to call location in array
test1 = arr
End Function
Sub test()
Dim varTest As Variant
varTest = test1(0) 'outputs "AJ" in immediate window
Debug.Print varTest
End Sub
Now you can debug.print your array values, or set to varTest based on the location in the array.
Edit: Tested after my consolidating comments and recognized that there was not an actual output for test1 as an array at the end of the function, so had to go back and add a second array to set test = allowing an array output from a function.
Your code is running as it should.
The test1 function assigns the value AJ to the test1 variable, and then it assigns the value A to the test1 variable.
You could assign the value 50 in your test procedure and it will return A.
I think this is the code you're after:
Function test1(num1) As String
' Dim MyArray As Variant
' MyArray = Array("AJ", "A")
'OR
Dim MyArray(0 To 1)
MyArray(0) = "AJ"
MyArray(1) = "A"
If num1 >= LBound(MyArray) And num1 <= UBound(MyArray) Then
test1 = MyArray(num1)
Else
test1 = "Item not here"
End If
End Function
Sub test()
Dim varTest As String
'Return the second item in the array from the function.
varTest = test1(1)
MsgBox varTest
'Return the first item in the array from the function.
varTest = test1(0)
MsgBox varTest
'Returns "subscript out of range" error as array is only 2 elements in size (0 and 1).
'The error is dealt with in the function using the IF....ELSE...END IF block and returns
'"Item not here" instead.
varTest = test1(2)
MsgBox varTest
End Sub
I solved this by using declaring the variables even when option explicit is not used.
The old code runs without throwing errors even when the variable is not declared and option explicit is also not used. But, for some reasons, it doesn't read / write undeclared variables as expected.
Now as per #cyril suggestion, I declared the variables being used and run the code. This time code ran as expected.
This happened for multiple of variables and at different stages in the code.

Error When Running VBA Code

I am Trying to run this code but it keeps giving me an error message while compiling
Argument not optional
I am using a function called csvRange
Sub CS()
csvRange()
End Sub
Function csvRange(FirstNum, SecondNum) As Double
i As Integer
For i = FirstNum.Value To SecondNum.Value
csvRange = csvRange & i & "+"
Next
End Function
can anyone help.
you want to call csvRange() but csvRange requires 2 arguments to pass.
And you forgot to save the return value.
for example
Sub CS()
var first = 1
var second = 50
var result
result = csvRange(first, second)
End Sub
Function csvRange(FirstNum, SecondNum) As Double
i As Integer
For i = FirstNum.Value To SecondNum.Value
csvRange = csvRange & i & "+"
Next
End Function
A couple of remarks:
- You call the function csvrange without parametervalues which you did not define as being optional.
- You do nothing with the value the function returns
- the i is an integer and the result a double. it is bad practice to mix them both in your for-next loop
Your code requires a few fixes:
1) Use appropriate arguments for csvRange.
2) Use the return value of csvRange for something (this is not mandatory, but typically required in well designed code).
3) Declare the type of arguments for csvRange.
4) You seem to be using csvRange to get a String. Change code accordingly.
You would use something like
Sub CS()
Dim rng1 As Range, rng2 As Range
Set rng1 = ...
Set rng2 = ...
Set retval As String
retval = csvRange(rng1, rng2)
End Sub
Function csvRange(FirstNum As Range, SecondNum As Range) As String
i As Integer
csvRange = ""
For i = FirstNum.Value To SecondNum.Value
csvRange = csvRange & Cstr(i) & "+"
Next i
End Function
PS1: Your output will end with a trailing "+". Perhaps this is not what you want.
PS2: I do not have a system to test this code.

Check if a string contains another string

I want to find if a string contains a ","(comma) in it. Do we have any other option other than reading char-by-char?
Use the Instr function (old version of MSDN doc found here)
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
will return 15 in pos
If not found it will return 0
If you need to find the comma with an excel formula you can use the =FIND(",";A1) function.
Notice that if you want to use Instr to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare (or just 1 for die-hards).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
will give you a value of 14.
Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.
You can also use the special word like:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.
Per #rene's answer...
Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
...would return 20 to pos, instead of 6.
Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:
Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function
You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA
Option Explicit
Public Sub test()
Debug.Print ContainsSubString("bc", "abc,d")
End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
'substring = string to test for; testString = string to search
ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")
End Function

Resources