I've been absolutely tearing my hair out over this. Is there a simple way to pull a variable value from a string? I'm trying to use this to cleanly check the value of multiple similar variables. Example:
Dim BoxString As String
For i = 1 To 100
BoxString = "response = Report" & i & "Box.value"
Application.Evaluate (BoxString)
If response = True Then
'...
End If
Next i
For context, I'm using this to evaluate which boxes on a UserForm were selected, and perform an action for each one that was.
Thanks so much in advance!
Related
Note. Check if the TextBox1 is empty is easy by using TextBox1.Value = "".
But the problem is when the user hit the spacebar, TextBox1 will still recognize it as a value. In such case, my data will appear as an empty cell with 1 space inside. So my question is, is there any method to check TextBox1.value for empty and also not consist of space whether there are 1 or more space? Million thanks to all.
A common trick is to check like this:
trim(TextBox1.Value & vbnullstring) = vbnullstring
this will work for spaces, empty strings, and genuine null values
Most terse version I can think of
Len(Trim(TextBox1.Value)) = 0
If you need to do this multiple times, wrap it in a function
Public Function HasContent(text_box as Object) as Boolean
HasContent = (Len(Trim(text_box.Value)) > 0)
End Function
Usage
If HasContent(TextBox1) Then
' ...
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
For various reasons, I need to concatenate a text of the form [NAME].Value by changing the value of NAME to an inputbox entry.
Something like this:
Sub example()
data_in = InputBox("Give me something: ")
mystring1 = "[" & data_in & "].Value"
a = Evaluate(mystring1) 'I know this is wrong, but I don't know how to do so.
End Sub
I know it can be done in other ways, and the example in which I want to use this code is not exactly this one, and while it can be done in several ways here, in the original code it can only be done this way.
I want, based on the input in the imputbox, to concatenate the string in whatever way, and subsequently cast that string as code to store the value in another variable, to be used later in the code.
I am not able to get VBA to read the string text as code. I have seen that there is a way that consists of creating a macro from this first macro, execute it, and then delete the recently created macro. The problem with this solution is that doing that I can't save the variable when returning to the initial macro (I don't want to use global variables).
Surely there must be a way?
Thank you very much.
EDIT: The code above returns Error 2015
In order to use a string as if it was code, you can use the evaluate function (exists in most languages)
The official documentation mentions this example:
[a1].Value = 25
Evaluate("A1").Value = 25
trigVariable = [SIN(45)]
trigVariable = Evaluate("SIN(45)")
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1]
Set firstCellInSheet = _
Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")
I have figured out the easiest way to do it, sorry for posting the question so soon.
Thanks to #Andreas for the solution. I'll write it here in case than could be useful to someone.
Sub example()
data_in = InputBox("Give me something: ")
a = Range(data_in).Value
Debug.Print a
End Sub
In the end the simplest thing is the last thing you try...
This is for VB.NET 2017. I am creating a program and keeping score with the best time. The timer in the program runs like a stopwatch. I would like at the end to compare the best record from a past game with the current time of a new game. If the new game has a faster time then I would like to replace it on the data file. I can do that just fine but sometimes it will put a slower time ahead of the fastest time. I have tried multiple scenarios and cannot get it consistent. If anyone could help that would be appreciated very much. I have some message boxes so I can see some outcomes. They will be commented out later when it is working properly.
If TotalBalls = 2 And SelectPoison = 2 Then
tmrTime.Enabled = False
CurrentScore = lblTime.Text
MsgBox("You win.")
'''''''''''''''''''''''''''''''''''''''''''''''''''
' CurrentScore = lblTime.Text
MsgBox("Current Time is " & CurrentScore)
NewScoreCheck = String.Compare(CurrentScore, RecordHighScore)
MsgBox(NEwScoreCheck)
'NewScoreCheck will be less than 0 if CurrentScore is less (alphabetically) than RecordhighScore
'NewScoreCheck will be greater than 0 if RecordHighSchore is greater than CurrentScore
If NewScoreCheck < 0 Then
MsgBox(CurrentScore)
Try
MsgBox("In the try statement. Writing new time")
Dim FileWrite As System.IO.StreamWriter
FileWrite = New System.IO.StreamWriter("PoisonHighScore.TXT", False)
FileWrite.WriteLine(CurrentScore)
FileWrite.Close()
Catch
MsgBox("Saving error")
End Try
Else
MsgBox("Not the fastest time.")
End If
Else
MsgBox("You lose.")
End If
strExit = MsgBox("Do you want to play again?", vbYesNo)
If strExit = vbYes Then
Application.Restart()
End If
End Sub
Edit 1: I am using some variables as TimeSpan which is why I have the values CurrentScore and RecordHighScore as Strings. When I am using TimeSpan it will not store as an Integer and will return an error. I am looking for a way to compare two times but need to store them in such a way that they can be compared which is why I used the compare string method mentioned above. I understand after looking at the solution below as to why I cannot. My question now becomes how do I store them since it cannot be stored as double, single, or integer?
To make it a little more clear think of two racers who finish with two different times and those times being unpredictable. The fastest time would win and we would write to the text file (which I know how to do) the time of the winner.
P.S. I have also tried the CInt(CurrentScore) < CInt(RecordHighScore) but that just returns an error too. Any help again would be greatly appreciated and thank you for taking the time to help me with this.
Right off the bat it looks like you're doing some implicit type conversions such as:
CurrentScore = lblTime.Text
Presumably CurrentScore is a numeric data type (like an Integer or Double), but you're setting the value equal to a String. To correct those errors, turn Option Strict on. Looking even deeper, this appears to be your problem because you use the String.Compare method to compare the scores alphabetically. To give you an example, String.Compare returns -1 when you pass 1112 and 121 as your current score and high score respectively, but obviously 121 is quicker than 1112.
What you need to do is convert all numeric values as numeric data types and then compare them using the appropriate comparison operator.
If you want the Timer to behave like a stopwatch then why not use a StopWatch? If you use a StopWatch, you can get the ElapsedMilliseconds which returns a long. The Stop method only pauses the timer; you need to call the Reset method to reset the StopWatch to zero. Call this after you collect the ElapseMilliseconds into a variable.
NewScoreCheck = String.Compare(CurrentScore, RecordHighScore) Strings are not compared in the same way numbers are.
Dim a As String = "72"
Dim b As String = "100"
If String.Compare(a, b) < 0 Then
MessageBox.Show("a comes first")
Else
MessageBox.Show("b comes First")
End If
Result b comes first!
Using a MsgBox to check values is not a great idea. Visual Studio has all sorts of great debugging tools. Inevidibly you will forget to remove a MsgBox; I have :-). Use Debug.Print which will not be in the release version.
Dim sw As New Stopwatch()
Private Sub BeginGame()
sw.Start()
End Sub
Private Sub OPCode2()
Dim TimeInMilliseconds As Long = sw.ElapsedMilliseconds
Dim TotalBalls As Integer = 2
Dim SelectPoison As Integer = 2
Dim RecordHighScore As Long
Dim CurrentScore As Long
If TotalBalls = 2 And SelectPoison = 2 Then
sw.Stop()
CurrentScore = sw.ElapsedMilliseconds
sw.Reset() 'So you can play again and get a new time
MsgBox("You win.")
'''''''''''''''''''''''''''''''''''''''''''''''''''
Debug.Print($"Current Time is {CurrentScore}")
If CurrentScore > RecordHighScore Then
Try
Debug.Print("In the try statement. Writing new time")
Dim FileWrite As System.IO.StreamWriter
FileWrite = New System.IO.StreamWriter("PoisonHighScore.TXT", False)
FileWrite.WriteLine(CurrentScore.ToString)
FileWrite.Close()
Catch
MsgBox("Saving error")
End Try
Else
MsgBox("Not the fastest time.")
End If
Else
MsgBox("You lose.")
End If
Dim strExit As MsgBoxResult
strExit = MsgBox("Do you want to play again?", vbYesNo)
If strExit = vbYes Then
'Not a good way to do this, clear your variables and UI
Application.Restart()
End If
End Sub
I programmed a communication tool for the production floor. This tool will register what they have done, who has done it and on what time.
The following should check whether the textbox value equals the value in the worksheet or if the textbox (textbox is TextTools1) is empty. If this is true, then nothing should happen and the thus the value of the textbox is gonna stay the same.
If the textbox is not empty or is not equal to what has been previously saved in the worksheet (thus the value has changed), then it should be registered which operator has done it and what date and what time.
It works when the textbox is empty, but when the value of the textbox has stayed the same (thus TextTools.value=ActiveCell.Offset(0,23).value (Correct)) it still adds the operators name, date and time.
Something is going wrong when trying to compare the textbox value and the cell value, but cant put my finger on it.
Sheets("Checklist & overdracht").Visible = True
Sheets("Checklist & overdracht").Select
If TextTools1.Value = Range("AZ1").Value Or TextTools1.Value = Empty Then
Sheets("Checklist & overdracht").Select
rowloc1.Value = ActiveCell.Row
ActiveCell.Offset(0, 23).Value = TextTools1.Value
Else
Sheets("Checklist & overdracht").Select
rowloc1.Value = ActiveCell.Row
ActiveCell.Offset(0, 23).Value = TextTools1.Value & " " & "(" & cboOperator.Value & " " & Format(DateValue(CStr(Now)), "short date") & " " & Format(TimeValue(CStr(Now)), "hh:mm") & ")"
End If
Edit; changed it to the code above. I tested this in another userform (and used f8) and it works brilliantly, but when I put in the userform that will actually run this code, than it doesnt have the same result...
Edit2; So apparently something goes wrong with Range(AZ1).Value reference. Because when I enter a random value instead of the range and then run the code, it does work. Is there a different way of referencing?
Ok based on your comments
Stop using active cell when code from a user form is communicating to the compiler what sheet is what. You need to fully qualify what sheet you are using. Im not entirely sure where in the code the active sheet is being set but I am fairly certain the answer is never. Another reason selecting and referencing .ActiveWhatever is bad is a cardinal sin of vba is interacting with the actual application object instead of doing everything in memory. It bogs everything done and performance suffers considerably. When you start writing pretty dense stuff then you will inevitably suffer from issues where the compiler gets confused as to what thing it should be looking at and you'll have a grand ol' time of troubleshooting that nonsense.
Also, it might be a good idea to check for more than just "=Empty". What if there is a null or empty string? I tend to check for:
.value = "" OR ISNULL(.Value)=True OR .Value = vbNullstring
this isnt real feedback though - tons of people have different ways of doing the same thing.
Try:
Thisworkbook.Sheets("YOURSHEETNAME").Range("YOURRANGE").Offset(0,23).Value = Someothervalue.
Let me know if youre still facing issues.
I'm working making a loop to get data out of a combo form.
Analysis_1 is the first variable
Analysis_1_ComboB is the first ComboBox from the screen
Analysis_1 = Me.Analysis_1_ComboB.Column(0)
Analysis_2 = Me.Analysis_2_ComboB.Column(0)
Analysis_3 = Me.Analysis_3_ComboB.Column(0)
etc etc
as single lines, it is working I do want to work with a loop
for counter = 1 to 9
Analysis_&Counter = Me.Analysis_&Counter&_ComboB.Column(0)
next counter
unfortunately, this is not working, who can help me out here?
Unfortunately, you cannot dynamically specify variable names. (You can usually find a way to dynamically access various objects, especially if they are accessible be a "Name" index.)
The best way to achieve what you want to do is make your variables an array, e.g.:
Dim Analysis(1 To 9) As String
For counter = 1 To 9
Analysis(counter) = Me.Controls("Analysis_" & counter & "_ComboB").Column(0)
Next counter
MsgBox "Value from Analysis_5_ComboB is " & Analysis(5)
(This code assumes that your ComboBoxes are on a UserForm and therefore dynamically accessible via the form's Controls collection.)