VBA userform - Dynamic textbox default value - vba

I have two TextBox in my userform. One is for entering the Name, and the other one is for entering the income.
Now I create a modeless userform, so that user can keep insert the data
Suppose I already have list of Name. For example: Marry, Jamie, Michael
Is it posible to set this list as a default value for Name TextBox?
For example:
After click the button, the userform Pop up and Shows as follow:
Name: Marry
Income: ""
After I enter the income, and click "OK" buttom, the userform will Pop up again.
This time it Shows like this:
Name: Jamie
Income: ""
If my question is not clear enough, please tell me and I will explain it more detailed. Thanks in advance.
Update:
I add my code here to make my question clearer. However, the "story" of my code is a Little bit different. The user will insert the Portfolio ID, Budget value and the date into userform. Then the macro will filter the table in sheet "ALL_List".
Based on Portfolio ID and date, there will be only one line data in that table after filtering. The Budget column for this line of data should be empty. The Macro should automatically insert the Budget value, which was recorded in userform, into Budget column.
There are, for example, 5 ID and 5 Budget value:
Date / ID / Budget
29/06/2018 / 12541 / 336521
29/06/2018 / 4521 / 658882
29/06/2018 / 44359 / 4587996
29/06/2018 / 10223 / 148665
29/06/2018 / 74 / 658324
So, when the first time userform Pop up. I hope there will be a Default ID value "12541" in the Portfolio ID TextBox. After I enter the date and Budget value and click the button "Enter", the Budget value will insert to the Budget column in sheet "ALL_List". Then the userform Pop up again. This time the Default value for ID will be 4521.
After the final Default ID (74) Show up and I enter the value and click Enter, I hope the userform will still Pop up and this time the value of Portfolio ID TextBox will be empty (because there could be other ID which the user wants to insert.)
Hope my descripition is clear. If there is any question, please don't hesitate to inform me. Much Thanks!
Sub Budget_Adjustment()
Dim frm As New UserFormBudget
frm.Show vbModeless
End Sub
Private Sub ButtonClose_Click()
Unload Me
End Sub
Private Sub ButtonEnter_Click()
InsertBudget
End Sub
Private Sub InsertBudget()
Dim UpdateDate As String
Dim PortfolioID, Budgetvalue As Long
UpdateDate = TextBoxDate.Value
PortfolioID = TextBoxID.Value
Budgetvalue = TextBoxBedget.Value
UpdateDate = CDate(UpdateDate)
Sheets("ALL_List").Activate
ActiveSheet.AutoFilterMode = False
Range(Cells(1, 1), Cells(Cells(Rows.Count, 7).End(xlUp).row, 7)).AutoFilter Field:=1, Criteria1:=UpdateDate
Range(Cells(1, 1), Cells(Cells(Rows.Count, 7).End(xlUp).row, 7)).AutoFilter Field:=3, Criteria1:=PortfolioID
Cells(Cells(Rows.Count, "A").End(xlUp).row, "F").Value = Budgetvalue
ActiveSheet.AutoFilterMode = False
TextBoxID.Value = ""
TextBoxBedget.Value = ""
TextBoxID.SetFocus
End Sub
Private Sub TextBoxBedget_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
ButtonEnter_Click
End If
End Sub
Private Sub UserForm_Activate()
'Empty TextBoxID
TextBoxID.Value = ""
'Empty TextBoxBedget
TextBoxBedget.Value = ""
'Empty TextBoxDate
TextBoxDate.Value = ""
'Set Focus on NameTextBox
TextBoxDate.SetFocus
End Sub

...
EDIT:
Edited your code a little bit based on the new information you provided. Now, you just enter your ID's you want to edit before hand in the sheet named "list".
I added sheet named "List" :
This code goes in area when you right-click UserFormBudget > View Code:
Private Sub ButtonClose_Click()
Dim lastListRow As Long
With ThisWorkbook.Worksheets("List")
lastListRow = .Cells(.Rows.Count, 1).End(xlUp).row
.Range("A4:A" & lastListRow).Interior.ColorIndex = 0
End With
Unload Me
End Sub
Private Sub ButtonEnter_Click()
InsertBudget
End Sub
Private Sub InsertBudget()
Dim UpdateDate As String
Dim PortfolioID As Long
Dim Budgetvalue As Long
Dim lastListRow As Long
Dim row As Long
UpdateDate = TextBoxDate.Value
PortfolioID = TextBoxID.Value
Budgetvalue = TextBoxBedget.Value
If Len(UpdateDate) > 0 Then
UpdateDate = CDate(UpdateDate)
Else
MsgBox "Need to enter a date"
Exit Sub
End If
With Worksheets("ALL_List")
.Activate
.AutoFilterMode = False
.Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 7).End(xlUp).row, 7)).AutoFilter Field:=1, Criteria1:=UpdateDate
.Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 7).End(xlUp).row, 7)).AutoFilter Field:=3, Criteria1:=PortfolioID
.Cells(.Cells(.Rows.Count, "A").End(xlUp).row, "F").Value = Budgetvalue
.AutoFilterMode = False
End With
With ThisWorkbook.Worksheets("List")
lastListRow = .Cells(.Rows.Count, 1).End(xlUp).row
TextBoxID.Value = ""
For row = 5 To lastListRow
If .Cells(row, "A").Interior.Color <> RGB(255, 255, 0) Then
TextBoxID.Value = .Cells(row, "A").Value
.Cells(row, "A").Interior.Color = RGB(255, 255, 0)
Exit For
End If
If row = lastListRow Then
TextBoxDate.Value = ""
End If
Next
End With
TextBoxBedget.Value = ""
TextBoxID.SetFocus
End Sub
Private Sub TextBoxBedget_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
ButtonEnter_Click
End If
End Sub
And add this code in a module, so right-click project and insert new module, then paste:
Sub Budget_Adjustment()
Dim frm As New UserFormBudget
Dim lastListRow As Long
With ThisWorkbook.Worksheets("List")
lastListRow = .Cells(.Rows.Count, 1).End(xlUp).row
If lastListRow = 3 Then
frm.TextBoxDate.Value = ""
frm.TextBoxID.Value = ""
frm.TextBoxBedget.Value = ""
Else
frm.TextBoxID.Value = .Cells(4, "A").Value
frm.TextBoxBedget.Value = .Cells(4, "B").Value
.Cells(4, "A").Interior.Color = RGB(255, 255, 0)
End If
End With
frm.TextBoxID.SetFocus
frm.Show vbModeless
End Sub
Now, just right-click on the button on List sheet and assign it the macro Budget_Adjustment

Related

userform using variable of a commandbutton

I have a problem that I can not solve ... my problem is this:
I need to create a User Form that performs data search within 4 sheets, this data is the same only changing from year to year in the spreadsheets, but when I try to link my CommandBotton and use the variable in the error combo box ...
The business rule is as follows:
The User enters the employee's enrollment in this automatically pulls the data to the fields of the User Form, in case he wanted to change the worksheet he used the combo box to change between those worksheets and executing the same search but in different worksheets.
Public plan As Worksheet
Sub ComboBox1_Change()
Sheets(ComboBox1.ListIndex + 1).Activate
End Sub
Sub UserForm_Initialize()
For Each plan In ActiveWorkbook.Worksheets
ComboBox1.AddItem plan.Name
Next plan
End Sub
Sub bnt1_Click()
With ThisWorkbook.Sheets(plan).Range("A:A")
Set c = .Find(textCp.Value, LookIn:=xlValues, lookat:=xlPart)
If Not c Is Nothing Then
c.Activate
textCp.Value = c.Value
textName.Value = c.Offset(0, 1).Value
textAd.Value = c.Offset(0, 2).Value
text60.Value = c.Offset(0, 65).Value
text60_20.Value = c.Offset(0, 66).Value
text100.Value = c.Offset(0, 67).Value
text100_20.Value = c.Offset(0, 68).Value
textAdc.Value = c.Offset(0, 69).Value
textAdcT.Value = c.Offset(0, 70).Value
End If
End With
End Sub
Sub btnSair_Click()
Unload FormPes
End Sub
Simply use With plan.Range("A:A").
Here is how I would write the code. I fell like With c.EntireRow would make it easier to identify which columns that you are referring to, as opposed to c.Offset(0, 65).Value.
Sub bnt1_Click()
With plan.Range("A:A")
Set c = .Find(textCp.Value, LookIn:=xlValues, lookat:=xlPart)
If Not c Is Nothing Then
With c.EntireRow
textCp.Value = .Value
textName.Value = .Range("B1").Value
textAd.Value = .Range("C1").Value
text60.Value = .Range("BN1").Value
text60_20.Value = .Range("BO1").Value
text100.Value = .Range("BP1").Value
text100_20.Value = .Range("BQ1").Value
textAdc.Value = .Range("BR1").Value
textAdcT.Value = .Range("BS1").Value
End With
End If
End With
End Sub

VBA Excel 2 comboboxes issue

I am trying to make an application which lets you update sales condition details using two comboboxes.
See this screenshots for a demo:
1) Datasheet
2) this Userform concerns the creation of a new sales condition
3) a second Userform is required to modify the data and update it in the desired sheet
Regarding my source code for creating a new sales condition, you can find it in here:
Private Sub bAnnuler_Click()
Unload Me
End Sub
Private Sub bEnregistrer_Click()
Sheets("ConditionsVente").Activate
Range("A1").Select
Selection.End(xlDown).Select 'On se positionne sur la derniere ligne non vide
Selection.Offset(1, 0).Select 'On se décale d'une ligne vers le bas
'ActiveCell = txtNom.Value
ActiveCell.Offset(0, 3).Value = txtPrix
ActiveCell.Offset(0, 4).Value = txtDélai
End Sub
Private Sub bReinitialiser_Click()
txtPrix = ""
txtDélai = ""
End Sub
Private Sub cboFournisseur_Change()
End Sub
Private Sub UserForm_Initialize()
'initialiser combobox fournisseur
Dim Fournisseurs As Range
Dim Matieres As Range
Set Fournisseurs = Worksheets("Fournisseurs").Range("A2:A" & Worksheets("Fournisseurs").Range("A2").End(xlDown).Row)
Me.cboFournisseur.MaxLength = Fournisseurs.Count
Me.cboFournisseur.List = Fournisseurs.Value
'initialiser combobox matiere
Set Matieres = Worksheets("Matieres").Range("A2:A" & Worksheets("Matieres").Range("A2").End(xlDown).Row)
Me.cboMatiere.MaxLength = Matieres.Count
Me.cboMatiere.List = Matieres.Value
End Sub
I have two issues:
1) when I run this code, I create a new sales condition but what is saved in the sheet are just the price (prix in french) and the delay (délai in french) and in the columns of Suppliers (Fournisseurs in french) and Raw Material (Matiere in french) are still empty.
2) the second point, in order to make a userform which let me modify the sales condition in the desired sheet, what is the simplest way to realize it ?
For part 1 you need this:
Private Sub bEnregistrer_Click()
Dim nextRow as Integer
With Worksheets("ConditionsVente")
nextRow = .Range("A1").end(xlDown).Row + 1
.Range("A" & nextRow) = txtNom.Value
.Range("B" & nextRow) = txtMatiere.Value
.Range("C" & nextRow) = txtPrix
.Range("D" & nextRow) = txtDélai
End With
End Sub
For part 2 try this:
Private Sub btnSave_Click()
Dim Fournisseurs As Range, Fournisseur as range
Set Fournisseurs = Worksheets("Fournisseurs").Range("A2:A" & Worksheets("Fournisseurs").Range("A2").End(xlDown).Row)
For each Fournisseur in Fournisseurs
If Fournisseur = txtNom.Value And Fournisseur.offset(0, 1) = txtMatiere.Value Then
Fournisseur.offset(0, 3) = txtPrix
Fournisseur.offset(0, 3) = txtDélai
End if
Next Fournisseur
End Sub

Return data last row vba user form excel

I'm making some sort of football database where I would input data using a userform and where I want to retrieve data from my excel database.
I have a worksheet named "wedstrijden".
This worksheet contain the columns: Date, HomeTeam, AwayTeam, HomeScore,AwayScore, HomeOdds and AwayOdds.
My other worksheet is named "ingevenuitslagen".
This worksheet contains my userform called "UitslagenIngeven".
Using the code below I'm able to input my data from the userform to my "wedstrijden" worksheet:
Private Sub putAway_Click()
Dim ingevenuitslagen As Worksheet
Set ingevenuitslagen = ThisWorkbook.Sheets("wedstrijden")
NextRow = ingevenuitslagen.Cells(Rows.Count, 1).End(xlUp).Row + 1
ingevenuitslagen.Cells(NextRow, 1) = CDate(date_txt.Text)
ingevenuitslagen.Cells(NextRow, 2) = UitslagenIngeven.cboHomeTeam
ingevenuitslagen.Cells(NextRow, 3) = UitslagenIngeven.cboAwayTeam
ingevenuitslagen.Cells(NextRow, 4) = UitslagenIngeven.cboHScore
ingevenuitslagen.Cells(NextRow, 5) = UitslagenIngeven.cboAScore
ingevenuitslagen.Cells(NextRow, 6) = Val(UitslagenIngeven.hodds_txt.Text)
ingevenuitslagen.Cells(NextRow, 7) = Val(UitslagenIngeven.aodds_txt.Text)
End Sub
But now I want to return the values of the last row (worksheet "wedstrijden") to my userform using a button called "GetData", but I have no idea how to code that button.
This button will look like a lot with what you already have, something like this :
Private Sub GetData_Click()
Dim wedstrijden As Worksheet
Set wedstrijden = ThisWorkbook.Sheets("wedstrijden")
With wedstrijden
NextRow = .Cells(.Rows.Count, 1).End(xlUp).Row
UitslagenIngeven.date_txt.Text = .Cells(NextRow, 1)
UitslagenIngeven.cboHomeTeam = .Cells(NextRow, 2)
UitslagenIngeven.cboAwayTeam = .Cells(NextRow, 3)
UitslagenIngeven.cboHScore = .Cells(NextRow, 4)
UitslagenIngeven.cboAScore = .Cells(NextRow, 5)
UitslagenIngeven.hodds_txt.Text = .Cells(NextRow, 6)
UitslagenIngeven.aodds_txt.Text = .Cells(NextRow, 7)
End With
End Sub
How to work with a Data Array
Code to place in the UserForm to fill the data array :
Public DataA() 'This line should be at the top of the module
'Code to Set the dimension of the Data array
Private Sub UserForm_Initialize()
'5 is the number of information that you want to store
Dim DataA(5,0)
'----Or
'Take the number of column of your Data Base
Dim DataA(ThisWorkbook.Sheets("DB").Range("A1").End(xlToRight).Column + 1,0)
'Rest of your code
End Sub
'Code to add a data set to the data array
Private Sub CommandButton1_Click()
UnFilter_DB 'See below procedure
DataA(1) = Now()
DataA(2) = Me.Lb_Data.Caption
DataA(3) = Me.Lb_Year.Caption
DataA(4) = Me.Lb_BL.Caption
DataA(5) = Me.Lb_Country
ReDim Preserve DataA(Lbound(DataA,1) To Ubound(DataA,1), Lbound(DataA,2) To Ubound(DataA,2)+1)
End Sub
'Code to sent the data array to the DB
Private Sub CommandButton2_Click()
ReDim Preserve DataA(Lbound(DataA,1) To Ubound(DataA,1), Lbound(DataA,2) To Ubound(DataA,2)-1)
SetData DataA
End Sub
Procedure to print the data array that you pass from the user form :
Public Sub SetData(ByVal Data_Array As Variant)
Dim DestRg As Range, _
A()
'Find the last row of your DataBase
Set DestRg = ThisWorkbook.Sheets("DB").Range("Db_Val").Cells(ThisWorkbook.Sheets("DB").Range("Db_Val").Rows.Count, 1)
'Print your array starting on the next row
DestRg.Offset(1, 0).Resize(UBound(Data_Array, 1), UBound(Data_Array, 2)).Value = Data_Array
'Set Increasing ID
ThisWorkbook.Sheets("DB").Cells(Rows.Count, 1).End(xlUp) = ThisWorkbook.Sheets("DB").Cells(Rows.Count, 1).End(xlUp).Offset(-1, 0) + 1
End Sub
Sub to unfilter the DB you are working with (Here it is the Named Range Db_Val in DB sheet)
Public Sub UnFilter_DB()
'Use before "print" array in sheet to unfilter DB to avoid problems (always writing on the same row if it is still filtered)
Dim ActiveS As String, CurrScreenUpdate As Boolean
CurrScreenUpdate = Application.ScreenUpdating
Application.ScreenUpdating = False
ActiveS = ActiveSheet.Name
Sheets("DB").Activate
Sheets("DB").Range("A1").Activate
Sheets("DB").ShowAllData
DoEvents
Sheets(ActiveS).Activate
Application.ScreenUpdating = CurrScreenUpdate
End Sub

Changing invoice number automatically on workbook close but checking if it has to increase or not

I have this code below for my workbook that saves the workbook for me and also increases the invoice number by 1 based on the value in a certain cell:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Range("L5").Value = Range("L5").Value + 1
ThisWorkbook.Save
End Sub
So cell L5 starts with 1 and right now everytime the workbook is closed it will add +1 to it and save the book, so the next time it opens it will be 2,3,4,5 and so on.
The problem I have is that if someone closes it and open and closes it will keep adding numbers even though that invoice doesn't exit.
Is there anyway it can check a list of value from a column in sheet 2 to see if the current invoice number exists, if it does then add 1 and save, if not then leave the same number and save?
UPDATED SUBMIT CODE WITH CLEARING, SAVING, AND UPDAING INVOCE NUMBER. All cells are locked and protected except the cells in the refTable, those are editable by user but L5 is locked and needs to be editable by the VBA code only, not users.
Sub Submit()
Dim refTable As Variant, trans As Variant
refTable = Array("B = L5", "C = C5", "D=G5", "E=C10", "F=C9", "G=I9", "H=I10", "I=C13", "J=C14", "K=C15", "L=C16", "M=C17", "N=C18", "O=I13", "P=I14", "Q=I15", "R=I16", "S=I17", "W=H20")
Dim Row As Long
Row = Worksheets("TravelLog").UsedRange.Rows.Count + 1
For Each trans In refTable
Dim Dest As String, Field As String
Dest = Trim(Left(trans, InStr(1, trans, "=") - 1)) & Row
Field = Trim(Right(trans, Len(trans) - InStr(1, trans, "=")))
Worksheets("TravelLog").Range(Dest).Value = Worksheets("TravelRequest").Range(Field).Value
Next
If Worksheets("TravelRequest").CheckBox1.Value Then
Worksheets("TravelLog").Range("T" & Row).Value = "Yes"
Else
Worksheets("TravelLog").Range("T" & Row).Value = "No"
End If
If Worksheets("TravelRequest").CheckBox2.Value Then
Worksheets("TravelLog").Range("U" & Row).Value = "Yes"
Else
Worksheets("TravelLog").Range("U" & Row).Value = "No"
End If
If Worksheets("TravelRequest").CheckBox3.Value Then
Worksheets("TravelLog").Range("V" & Row).Value = "Yes"
Else
Worksheets("TravelLog").Range("V" & Row).Value = "No"
End If
Range("L5").Value = Range("L5").Value + 1
Range("I9:I10, I13:I17, H20, C5, C9:C10, C13:C18").Select
Selection.ClearContents
Dim OleObj As OLEObject
For Each OleObj In ActiveSheet.OLEObjects
If OleObj.progID = "Forms.CheckBox.1" Then
OleObj.Object = False
End If
Next OleObj
ThisWorkbook.Save
End Sub
Use goto in Workbook_BeforeClose with condition u mentioned like that
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If 'your_condition' = TRUE Then goto do_save
Range("L5").Value = Range("L5").Value + 1
do_save:
ThisWorkbook.Save
End Sub

VBA Userform not filled when first opened (possible memory issues)

VBA'ers,
I'll cut to the chase. I have a userform with all the bells and whistles(Label's,textboxes,listboxes,tabstrips,etc.). Currently I have three subs.
Here's my code. I know people only asked for the userform initialize but seeing all of it might help find the problem.
Private x As Single
Private y As Single
'------------------------------------------
Private Sub CommandButton1_Click()
Unload Me
End Sub
'------------------------------------------
Private Sub ListBox1_Click()
x = 2
y = 2
name = ListBox1.Value
'Loop to match names
Do Until name = Cells(x, y)
x = x + 1
Loop
'Changes lables on click <- I realize I can handle this better with listbox.values
Label2.Caption = Sheet2.Cells(x, 2) 'Name
Label5.Caption = Sheet2.Cells(x, 3) 'Current Positions
Label7.Caption = Sheet2.Cells(x, 4) 'Previous Positions
Label9.Caption = Sheet2.Cells(x, 5) 'DOB
Label11.Caption = Sheet2.Cells(x, 6) 'POB
Label13.Caption = Sheet2.Cells(x, 7) 'Party Affiliation
'Changes tab strip accordingly
Call TabStrip1_Change
'Handles Picture
If Cells(x, 8) <> "" Then
Image1.Picture = LoadPicture(ThisWorkbook.Path & Cells(x, 8))
Else
Image1.Picture = LoadPicture(ThisWorkbook.Path & "..\pics\nophoto.jpg")
End If
End Sub
'------------------------------------------
Private Sub TabStrip1_Change()
'Handle Tab Strip
If TabStrip1.Value = 0 Then
TextBox1.Value = Cells(x, 9)
ElseIf TabStrip1.Value = 1 Then
TextBox1.Value = Cells(x, 10)
Else
TextBox1.Value = Cells(x, 11)
End If
End Sub
'------------------------------------------
Private Sub UserForm_Initialize()
'Initialize global variables
x = 2
'Initialize lists within userform.
ListBox1.RowSource = "B2:B11"
'Set tab strip to first tab.
TabStrip1.Value = 0
TextBox1.Value = Sheet2.Cells(2, 9)
'Grab photo if path is in cell
If Cells(2, 8) <> "" Then
Image1.Picture = LoadPicture(ThisWorkbook.Path & Cells(2, 8))
Else
Image1.Picture = LoadPicture(ThisWorkbook.Path & "..\pics\nophoto.jpg")
End If
End Sub
The problem is that when I run the code, via vba or a commandButton (Userform1.show) its a coins flip on whether or not the userform populates the listbox. The labels are initialized correctly, but the listbox shows no text. If I continue to run and stop the macro, it will eventually work fine.
Is this a memory issue? Am I not activating the userform properly? Or is this due to sloppy coding?
Any suggestions would be appreciated.
Since we cannot see the full Userform_Initialize(), I assume you have only populated the list into listbox.
If you want a listbox to select something when it shows, you need to call something like ListBox1.ListIndex = 0 or the index of your default value. This must be after the list is populated.
UPDATE:
Thanks, I believe when it doesn't work, it's because the activesheet is not where you have the list items. Either put in full formula address or Range Name my test workbook is "Test.xlsm":
ListBox1.RowSource = "[Test.xlsm]Sheet1!B2:B11" ' Change Workbook and Sheet name to fit yours
or
ListBox1.RowSource = "Test.xlsm!MyListItems" ' Change Workbook name, Create and Change the name of the Range that contains the list items.