Context: I have 10 text boxes (ID1 To ID10) in a user form. The userform will also have a clear button, which will allow the user to clear all the values previously entered in the text box. For that I have inserted the below mentioned command in the Clear Button.
I have multiple commands with the same nomenclature except the number which varies with every text box. I wish to enter one command which will change number and execute all the commands.
Simple example given below: I wish to only put one command instead of the folloing:
Private Sub btnClear_Click()
'Empty ID1
ID1.Value = ""
'Empty ID2
ID2.Value = ""
'Empty ID3
ID3.Value = ""
.
.
. and so on till
.
'Empty ID10
ID10.Value = ""
End Sub
I know there is a solution to this, but since I am new cannot find on google using the correct key words. Sorry if this already exists. Any help will be appreciated. Thank you.
If these are TextBoxes on a UserForm, you will be able to do the following from a macro in the UserForm's code module:
Private Sub btnClear_Click()
Dim i As Long
For i = 1 To 10
Me.Controls("ID" & i).Value = ""
Next
End Sub
It's not possible to dynamically generate a variable and/or object name but, because the Controls collection can be indexed by the "name" of the control, it gives an alternative way of getting at the objects.
Adding in code for "option boxes" (OptionButtons? `CheckBoxes?) mentioned in comments, and changing the TextBox names to end with a "C":
Private Sub btnClear_Click()
Dim i As Long
For i = 1 To 10
Me.Controls("ID" & i & "C").Value = ""
Me.Controls("OB" & i).Value = False
Next
End Sub
Do you mean something like this?
For i=1 to 4
str="ID" & i & ".Value = ''"
Evaluate(str)
Next
Related
I have a fairly larger number of excel workbooks in a folder. Each workbook has one tab - Sheet1. Sheet1 includes three checkboxs: Checkbox 6, Checkbox 7 and Checkbox 8 in addition to some values in cells. I'm using this code:
Link to Code Used
to extract the cell values, but was hoping it would also be possible to determine the value (status checked or not checked) of each of the checkboxes. Is this possible? Note - None of the checkbox are linked to a particular cell.
There is no way to read anything from a closed file. Even the code you are linking to cannot do this. You will always need a program that opens the file, read the data from it, find the information you want and close it again.
For Excel files you usually use Excel, but it could be something else - I know that Python has an library to read & write Excel files (and there are more), but all of them have to open the file. Open means ask the operating system to read the data from disk, maybe set a lock, maybe later write it back, those kind of things.
That said, what you probably want is to access the data (in your case checkbox settings) without the sheet being visible. You can do so by set Application.ScreenUpdating = False, open the file, read the checkbox values, close the file and reset Application.ScreenUpdating = True. The user will not see anything. I strongly assume that the Excel4-Macro does the same, but you will not find many persons around that are able to deal with Excel4-Macros.
Now to be able to read the value of a checkbox, you need to know if you are dealing with ActiveX or Form controls (or both). I wrote a small prove of concept that can deal with both. You pass the name of a workbook, the name (or number) of a sheet and an array with the name of the checkboxes you want to read. Result is an array with the values of the checkboxes. However you need to know that the values of an ActiveX-checkbox is True or False (or Null if you allow TripleState), while for a form-checkbox it is xlOn or xlOff. In the case a sheet doesn't have a checkbox with the specific name, it will return an arbitrary number
Function getCheckBoxValueFromFile(filename As String, sheet As Variant, checkboxNames) As Variant
Const undefinded = -999
Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = Workbooks.Open(filename)
Dim i As Integer, res()
ReDim res(LBound(checkboxNames) To UBound(checkboxNames))
For i = LBound(checkboxNames) To UBound(checkboxNames)
Dim val As Long
val = undefinded
With wb.Sheets(sheet)
On Error Resume Next
' first try ActiveX-CheckBox
val = .OLEObjects(checkboxNames(i)).Object.Value
' if failed, try Form-CheckBox
If val = undefinded Then val = .CheckBoxes(checkboxNames(i)).Value
On Error GoTo 0
res(i) = val
End With
Next i
wb.Close False
getCheckBoxValueFromFile = res
Application.ScreenUpdating = True
End Function
To test the function:
Sub test()
Dim res, i, cbNames
cbNames = Array("CheckBox1", "Check Box 2")
res = getCheckBoxValueFromFile("C:\TEMP\Book1.xlsx", "Sheet1", cbNames)
For i = LBound(res) To UBound(res)
Debug.Print i & ": " & cbNames(i) & " -> " & res(i)
Next i
End Sub
I have a workbook that is used to organize daily orders for many customers into one sheet. The information that is entered into this sheet is then used to generate invoices for the customers.
This workbook has worked without any bugs for several months. However, recently it has started throwing up an error. I do not recall changing any of the code that could have caused this bug.
I have tried to figure this out by myself however, I am running out of ideas, here are a few things that I have found out:
The error ALWAYS pops up on the 7th iteration of the loop below (i.e when x=27).
The error ONLY has a problem with the (CheckBox " & x + 10) checkbox. I have tried running the loop avoiding checking the value of that particular checkbox and it works for all other checkboxes.
I read on another post that it might be a problem with using the dreaded .Select. So I got rid of it from everywhere that it might have been used.
My code
With ThisWorkbook.Worksheets("Invoice")
For x = 21 To 35
If .Shapes("Check Box " & x + 10).ControlFormat.Value = 1 And .Shapes("Check Box " & x + 25).ControlFormat.Value = 1 Then
MsgBox "Please only select one from the options (Return OR Discount)"
Exit Sub
Else
End If
Next x
End With
From what I understand, this error comes up when the object that I am working with does not support a property that I am trying to work with. What I do not understand is why the same lines of code, work "for 90%" of the loop (i.e the same type of object does support that property for 90% of the loop) but then it does not for one object of the same type.
For completeness, the code below is used to re-insert the checkboxes every time the workbook is used. This is done as another process might delete entire rows in the workbook, messing up the functionality of the check-boxes. So this makes sure the checkbox with the right name is in the correct cell:
Sub CheckBoxes()
ThisWorkbook.Worksheets("Invoice").CheckBoxes.Delete
With ThisWorkbook.Worksheets("Invoice")
For x = 5 To 19
Set cb = .CheckBoxes.Add(.Cells(x, "J").Left, .Cells(x, "J").Top, 4, 10)
With cb
.Name = "Check Box " & x + 26
.Caption = ""
.Display3DShading = False
End With
Set cb2 = .CheckBoxes.Add(.Cells(x, "K").Left, .Cells(x, "K").Top, 4, 10)
With cb2
.Name = "Check Box " & x + 41
.Caption = ""
.Display3DShading = False
End With
Next x
End With
End Sub
Any help or guidance in the right direction would be greatly appreciated!
Basically I need 2 inputbox. First inputbox will ask user to input a value and then prompt the 2nd inputbox after user click ok. The default value in the 2nd inputbox will be the value one cell to the right of the value in the first inputbox. This is what I want to achieve but the problem with inputbox is that the Cancel button which throw me error message or won't exit sub by any means.
So are there any other similar approaches in achieving my goal? Thanks a lot in advance!
InputBox(...) returns an empty string "" whenever the cancel button is pressed.
Knowing this, you could check to see if the input is "" for each input. If at any point along the way you encounter a cancel, you don't go any further.
This is demonstrated below using nested if statements.
Sub Macro1()
Dim x As String
Dim y As String
Dim yDefault As String
x = InputBox("Prompt One", "TITLE ONE")
If (x <> "") Then
yDefault = GetDefaultValue(x)
y = InputBox("Prompt Two", "TITLE TWO", yDefault)
If (y <> "") Then
MsgBox "X: " & x & vbCrLf & "Y: " & y, vbOKOnly, "RESULTS"
End If
End If
End Sub
Function GetDefaultValue(x As String) As String
' Your custom logic to grab the default value (whatever cell) goes here
GetDefaultValue = "DEFAULT(" & x & ")"
End Function
Since it is the values that you want, don't use the InputBox. Use the Application.Inputbox. If you press the magic key F1 in Excel and you type Application.Inputbox then you will see some magic text appear out of nowhere ;)
Here is an example usage.
Ret = Application.InputBox(prompt := "Please enter a value", type := 1)
Notice the type 1.
I can give you an exact answer but I am sure this will get you started ;) If not then post back :)
I am doing a form and I am finding myself with a weird problem with the TextBox.
I ask the user to insert some data and when it does, the TextBox changes the data.
An example, if the user inserts: 03/01/2013 and then the runs the form, the form instead to perform the code with the original data changes it, 01/03/2013.
I realized that always changes the day and the month, but never the year.
Extra information, I never "told" the form that the data it is gonna process it is a date.
I am struggling to make it work it out, so any help will be grateful.
If extra info is needed, please let me know it.
Code:
Private Sub CommandButton1_Click()
ThisWorkbook.Sheets("Hidden").Range("D1").Value = TextBox1.Value
ThisWorkbook.Sheets("Hidden").Range("D2").Value = TextBox2.Value
If TextBox1.Value < TextBox2.Value Then
If TextBox1.Value = "" Or TextBox2.Value = "" Then
MsgBox "...", vbExclamation, " ..."
Else
Run "macro"
ThisWorkbook.Sheets("SUMUP").Range("D11").Value = TextBox1.Value
ThisWorkbook.Sheets("SUMUP").Range("D12").Value = TextBox2.Value
End If
Else
MsgBox "..." & vbCrLf & "...", vbExclamation, " ..."
End If
End Sub
Thanks.
It's a VBA :]. Just convert to string by:
ThisWorkbook.Sheets("SUMUP").Range("D11") = Format(TextBox1.Value, "dd/MM/yyyy")
The most common issue related to your description:
you may be saving the users input into a cell. If So, please check the formatting of that cell.
Please provide more info on how the users input is stored. What datatype variable are you using to store the users input? What is the migration process for the input?
Post-Edit:
Format your cells ( simplest solution )
Range = Format(TextBox1.Value, "dd/mm/yyyy")
P.S.
You can store your users input in variables:
Dim txtb1, txtb2 As String
'ThisWorkbook.Sheets("Hidden").Range("D1").Value = TextBox1.Value
'ThisWorkbook.Sheets("Hidden").Range("D2").Value = TextBox2.Value
'
' instead of storing the value in cell, use variables ( now youre not going to need a "hidden" sheet
'
txtb1 = TextBox1.Value
txtb2 = TextBox2.Value
Hope this helps.
You have to change the date format of your system in order to accept the input format of your vba form. Go to
Start>Control panel>Clock
Language and Date, under Region and Language select Change date, time or number format. Under date and time format select the drop-down in front of Short Date then select dd-mmm-yy. Do thesame on long date and select dddd,mmmm dd,yyyy. I hope this would be helpful
The recent documents feature in Office is really useful, but I moved a file to a new directory and now I can't get Excel to stop hitting me with a "can't find this file" notification whenever I open a workbook. The Excel options seem only to control how many of these "recent documents" are displayed and not how many are actually saved. So I;'m wondering if there's a way in VBA to get at the list and remove the offending file.
Try this...
Public Function TestIt()
For i = 1 To Application.RecentFiles.Count - 1
Dim answer As String
answer = MsgBox("Delete " & Application.RecentFiles(i).Name, vbYesNo)
If answer = vbYes Then
answer = MsgBox("Are you sure?", vbYesNo)
If answer = vbYes Then
Application.RecentFiles(i).Delete
End If
End If
Next i
End Function
Not a VBA solution, but open up Regedit and you can remove files from the list at will.
The "File MRU" list is what you're after; for Excel 2007 it's under
HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\File MRU
Adjust the version number accordingly.
Close Excel, delete the offending file's entry from the list found there, and restart.
Facing the same issue I wrote this litte macro, removing all files from the recent file list, which are not accessible:
Public Function CheckRecentFiles() As Integer
Dim i As Integer, c As Integer
For i = Application.RecentFiles.count To 1 Step -1
'Debug.Print Application.RecentFiles(i).name
If Dir(Application.RecentFiles(i).name) = "" Then
Debug.Print "Delete from recent file list: " & Application.RecentFiles(i).name
Application.RecentFiles(i).Delete
c = c + 1
End If
Next i
Debug.Print c & " files removed."
CheckRecentFiles = c
End Function
Try the routine above not as function but as SUB.
And in the second line remove "-1" at its end, because the last entry will not be handled else.
Then the routine will work properly.
Based on #GunnarBernsteinI 's answer,I just added this to my Personal Macro Book. This is going to be super handy to clean up the temp files that I create to answer questions on SO.
Public Sub CleanRecentFiles()
Const ReviewEntry As Boolean = False
Dim f As RecentFile
For Each f In Application.RecentFiles
If Len(Dir(f.Name)) = 0 Then
f.Delete
ElseIf ReviewEntry Then
Debug.Print f.Name
Stop
End If
Next
End Sub
Demo
Open the Recent Workbooks List. Right click quickly and firmly between the icon and text for the document you wish to remove from the list. A dropdown list appears. It is the list which allows you to pin an item to the list. Choose Remove from List. It does work but it can be a bit tricky to time it correctly. If you are too slow it will just try to open the file.