VBA issue with finding cells - vba

So I've been working on a Holiday calendar for employees and I've got a problem which I cannot seem to find a solution for.
I have two buttons which are assigned to a VBA script and I'm having an issue with a holiday entry for it. I can't seem to be able to select a specific cell from the user form inputs to output the data. The code looks like this:
Private Sub ComboBox2_Change()
End Sub
Private Sub CommandButton1_Click()
Dim emptyRow As Long
'Make Sheet1 active
'Holiday Calendar.Activate
'Determine emptyRow
'ActiveCell = (A5)
'emptyRow = WorksheetFunction.CountA(Range("Employees")) + 1
NextRow = 5
Do Until Sheets("Holiday Calendar").Cells(NextRow, 4) = Username.Value
NextRow = NextRow + 1
Loop
'Transfer information
Cells(NextRow, 6).Value = TypeOfLeave.Value
Cells(NextRow, 5).Value = (EndDate.Value) + 1 - (StartDate.Value)
End Sub
Private Sub CommandButton2_Click()
Call UserForm_Initialize
End Sub
Private Sub CommandButton3_Click()
Unload Me
End Sub
Private Sub DTPicker1_CallbackKeyDown(ByVal KeyCode As Integer, ByVal Shift As
Integer, ByVal CallbackField As String, CallbackDate As Date)
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_Initialize()
'Empty UsernameTextBox
Username.Value = ""
'Empty TypeOfLeave ComboBox
TypeOfLeave.Clear
'Fill TypeOfLeaveComboBox
With TypeOfLeave
.AddItem "AL - Anual Leave"
.AddItem "WFH - Work From Home"
'.AddItem ""
End With
'Set Focus on UsernameTextBox
Username.SetFocus
End Sub
This is how the code for the whole user form looks.
Now what I need help with is when the user inputs the start and end date of their holiday it will then look for the username within the spreadsheet and place "AL-Anual Leave" and "WFH - Work From Home" accordingly in the dates that the user has provided.
So what I need is a piece of code that will find the date within the spreadsheet from the user form and input the values "Al" or "WFH"
If any of this is unclear please let me know and ill explain. I tried including pictures but don't have enough reputation so it's much harder. I can send the images in email if needed to explain better.

Based on our comments from above, I would like if you could give this code snippet a try first and let me know if it still isn't working.
Private Sub ComboBox2_Change()
End Sub
Private Sub CommandButton1_Click()
Dim emptyRow As Long
'Make Sheet1 active
'Holiday Calendar.Activate
'Determine emptyRow
'ActiveCell = (A5)
'emptyRow = WorksheetFunction.CountA(Range("Employees")) + 1
Username.Value = UsernameTextBox.Value
NextRow = 5
Do Until Sheets("Holiday Calendar").Cells(NextRow, 4) = Username.Value
NextRow = NextRow + 1
Loop
'Transfer information
Cells(NextRow, 6).Value = TypeOfLeave.Value
Cells(NextRow, 5).Value = (EndDate.Value) + 1 - (StartDate.Value)
End Sub
Private Sub CommandButton2_Click()
Call UserForm_Initialize
End Sub
Private Sub CommandButton3_Click()
Unload Me
End Sub
Private Sub DTPicker1_CallbackKeyDown(ByVal KeyCode As Integer, ByVal Shift As
Integer, ByVal CallbackField As String, CallbackDate As Date)
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_Initialize()
'Empty UsernameTextBox
Username.Value = ""
'Empty TypeOfLeave ComboBox
TypeOfLeave.Clear
'Fill TypeOfLeaveComboBox
With TypeOfLeave
.AddItem "AL - Anual Leave"
.AddItem "WFH - Work From Home"
'.AddItem ""
End With
'Set Focus on UsernameTextBox
Username.SetFocus
End Sub

Related

Excel Listbox inconsistently has no value after setting the Listindex

I have a simple UserForm with two Listboxes and two Textboxes that contain the value of the currently selected Listitem. I am having a bizarre bug where one of the boxes will not populate when the form loads. If I close the form and load it again, then the opposite box will not load. If I close and reload a third time, then it loads the first box but not the second again. Repeat ad nauseum.
First Load:
Second Load:
The code should have both Textboxes populated at startup. What is the source of this bug?
Private Sub UserForm_Initialize()
Dim i As Long
For i = 1 To 4
ListBox1.AddItem "Item A - " & i
Next i
ListBox1.ListIndex = 0
End Sub
Private Sub ListBox1_Change()
Dim i As Long
ListBox2.Clear
For i = 1 To 3
ListBox2.AddItem "Item B - " & i
Next i
ListBox2.ListIndex = 0
TextBox1.Value = ListBox1.Value
End Sub
Private Sub ListBox2_Change()
TextBox2.Value = ListBox2.Value
End Sub
This answer is from Yow3Ek as much as from anyone. This code runs as tested without error or previous problem. Thanks guys, I learned something today. It was firing on the clear.
Private Sub UserForm_Initialize()
Dim i As Long
For i = 1 To 4
Me.ListBox1.AddItem "Item A - " & i
Next i
Me.ListBox1.ListIndex = 0
End Sub
Private Sub ListBox1_Change()
Dim i As Long
Me.ListBox2.Clear
For i = 1 To 3
ListBox2.AddItem "Item B - " & i
Next i
Me.ListBox2.ListIndex = 0
Me.TextBox1.Value = Me.ListBox1.List(Me.ListBox1.ListIndex)
End Sub
Private Sub ListBox2_Change()
If Me.ListBox2.ListIndex = -1 Then Exit Sub
Me.TextBox2.Value = Me.ListBox2.List(Me.ListBox2.ListIndex)
End Sub

VBA Excel assistance in userform refedit control

I have setup my userform perfectly so that when the user enters the date it shows in a label box in the userform it self.
All I'm struggling with is using my output frame as shown, which contains a refEdit control and a button. I am trying to have the date to be placed on any worksheet cell.
Image of my userform:
So far the code that I have come up with is the following:
Private Sub avgBtn_Click()
Dim range1 As String
Dim newdate As String
range1 = TextBox3.Value + "," + TextBox1.Value + " " + TextBox2.Value + "," + TextBox4.Value
newdate = range1
Label7.Caption = newdate
End Sub
Private Sub cancelBtn_Click()
Unload Task2
End Sub
Private Sub CommandButton1_Click()
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
End Sub
Private Sub UserForm_Click()
Unload UserForm1
End Sub
For the refedit control and command button I have come up with this code but it is giving me errors:
Sub CommandButton2_Click()
Dim myCell As Range
Set myCell = Nothing
On Error Resume Next
Set myCell = Range(Me.RefEdit1.Value).Areas(1).Cells(1)
myCell.value = Label7.Caption
End Sub
Would appreciate any feedback in regards to this code.

(Excel VBA) How to Show AutoComplete Feature of a ComboBox as a DropDown List

I would like the following code to add values to a combobox, then when the user inputs characters into the combobox, the dropdown feature of the combobox will show only those items which contain those characters, similarly to the way the Google Search Bar works.
(source: intersites.com)
Code Edit:
Option Explicit
Option Compare Text
Public LC As Long
Public Count As Integer
Dim ComboArray() As String
'Initializes the userform, and saves values from database into an array
Private Sub UserForm_Initialize()
LC = Cells(1, Columns.Count).End(xlToLeft).Column
ReDim ComboArray(1 To LC)
For Count = 1 To LC
ComboArray(Count) = Cells(1, Count).Value
Next Count
End Sub
'Prevents changes if the down key is pressed?
Private Sub ComboBox_SiteName_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Application.ScreenUpdating = False
End Sub
'Adds values to combobox if they contain the string input by user
Private Sub ComboBox1_Change()
Dim pos As Integer
Dim i As Integer
ComboBox1.Clear
For Count = 1 To LC
pos = InStr(1, ComboArray(Count), ComboBox1.Value)
If pos <> 0 Then
With ComboBox1
.AddItem Cells(1, Count)
End With
End If
Next Count
End Sub
Here is a simple example, which may need refinement for your purposes, but illustrates the general principles of using the KeyPress event to build a string of user input, and compare that to each item in the list, effectively filtering the list to values that start with the input string.
This needs some refinement to handle backspacing, deleting, etc., which I tried to do, but didn't get as far as I'd like.
Code:
Option Explicit
Dim cbList As Variant
Dim userInput$
'### USERFORM EVENTS
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 8, 48
'MsgBox "Backspace"
Debug.Print "Backspace"
If userInput <> "" Then
userInput = Left(userInput, Len(userInput) - 1)
End If
Case 46
'MsgBox "Delete"
Debug.Print "Delete"
userInput = Replace(userInput, ComboBox1.SelText, "")
End Select
End Sub
Private Sub UserForm_Activate()
Dim cl As Range
userInput = ""
For Each cl In Range("A1:A8")
Me.ComboBox1.AddItem cl.Value
Next
Me.ComboBox1.MatchRequired = False
cbList = Me.ComboBox1.List
End Sub
Private Sub UserForm_Terminate()
userInput = ""
End Sub
'#### END USERFORM EVENTS
'#### COMBOBOX EVENTS
Private Sub ComboBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Me.ComboBox1.List = cbList
' Capture the user input in module variable
userInput = userInput & Chr(KeyAscii)
Debug.Print "input: " & userInput
Debug.Print KeyAscii
Dim i As Long, itm
For i = Me.ComboBox1.ListCount - 1 To 0 Step -1
itm = Me.ComboBox1.List(i)
If Not StartsWith(CStr(itm), userInput) Then
Me.ComboBox1.RemoveItem i
End If
Next
If Me.ComboBox1.ListCount = 0 Then
Me.ComboBox1.List = cbList
Else
Me.ComboBox1.List = Me.ComboBox1.List
End If
Me.ComboBox1.DropDown
End Sub
'#### END COMBOBOX EVENTS
'#### HELPER FUNCTIONS
Function StartsWith(imtVal$, inputStr$, Optional caseSensitive As Boolean = False)
', Optional caseSensitive As Boolean = False
'If Not caseSensitive Then
imtVal = LCase(imtVal)
inputStr = LCase(inputStr)
'End If
StartsWith = VBA.Strings.Left(imtVal, Len(inputStr)) = inputStr
End Function
'#### END HELPER FUNCTIONS

Incorporating refedit into Vlookup userform

I have a vlookup userform which autofills the details in the form based on the seat n°.
Now I want to incoroporate a ref edit to paste these data from the text box to the cells the user chooses with the refedit. Hence i would need some help in going about these. This is the code i have used. I potentially want to insert 3 refedit boxes for user to select the cell they want to paste each of the data (Name,Dept and Ext No.) from the textbox.
See my code below:
Option Explicit
Private Sub Frame1_Click()
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim answer As Integer
answer = TextBox1.Value
TextBox2.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 2, False)
TextBox3.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 3, False)
TextBox4.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 4, False)
End Sub
Private Sub TextBox2_Change()
End Sub
Private Sub TextBox3_Change()
End Sub
Private Sub TextBox4_Change()
End Sub
Private Sub CancelButton_Click()
Unload Me
End
End Sub
I have tried figuring out a code to solve this issue but I am getting an object required error. My rngcopy would be textbox2.value (Name) and the rngpaste location would be the ref edit 1.
This is the code
Private Sub PasteButton_Click()
Dim rngCopy As Range, rngPaste As Range
Dim wsPaste As Range
Dim answer As Integer
answer = TextBox1.Value
If RefEdit1.Value <> "" Then
TextBox2.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 2, False)
Set rngCopy = TextBox2.Value
Set wsPaste = ThisWorkbook.Sheets(Replace(Split(TextBox2.Value, "!")(0), "'", ""))
Set rngPaste = wsPaste.Range(Split(TextBox2.Value, "!")(1))
rngCopy.Copy rngPaste
Else
MsgBox "Please select an Output range"
End If
End Sub
You should get the row index with Match and expose it to the form so it can be used by the copy function.
And to set the target pointed by a Ref control, just evalute the .Value property with Range():
Range(RefEdit.Value).cells(1, 1) = Worksheet.Cells(row, column)
The form:
The code:
' constants to define the data
Const SHEET_DATA = "L12 - Data Sheet"
Const COLUMN_SEAT = "B"
Const COLUMNN_NAME = "C"
Const COLUMN_DEPT = "D"
Const COLUMN_EXTNO = "E"
Private Sheet As Worksheet
Private RowIndex As Long
Private Sub TxtSeatNo_Change()
Dim seatno
'clear the fields first
Me.TxtName.value = Empty
Me.TxtDept.value = Empty
Me.TxtExtNo.value = Empty
RowIndex = 0
If Len(TxtSeatNo.value) Then
Set Sheet = ThisWorkbook.Sheets(SHEET_DATA)
On Error Resume Next
' get the seat number to either string or double
seatno = TxtSeatNo.value
seatno = CDbl(seatno)
' get the row index containing the SeatNo
RowIndex = WorksheetFunction.match(seatno, _
Sheet.Columns(COLUMN_SEAT), _
0)
On Error GoTo 0
End If
If RowIndex Then
' copy the values from the sheet to the text boxes
Me.TxtName.value = Sheet.Cells(RowIndex, COLUMNN_NAME)
Me.TxtDept.value = Sheet.Cells(RowIndex, COLUMN_DEPT)
Me.TxtExtNo.value = Sheet.Cells(RowIndex, COLUMN_EXTNO)
End If
End Sub
Private Sub BtCopy_Click()
If RowIndex < 1 Then Exit Sub
' copy the current values to the cells pointed by the ref controls
If Len(Me.RefName.value) Then _
Range(Me.RefName.value) = Sheet.Cells(RowIndex, COLUMNN_NAME)
If Len(Me.RefDept.value) Then _
Range(Me.RefDept.value) = Sheet.Cells(RowIndex, COLUMN_DEPT)
If Len(Me.RefExtNo.value) Then _
Range(Me.RefExtNo.value) = Sheet.Cells(RowIndex, COLUMN_EXTNO)
End Sub
Private Sub BtlClose_Click()
' close the form
Unload Me
End Sub
You are declaring your rngCopy as a Range Object and then later on you are binding it to a .value method of the range object.
Set rngCopy = TextBox2.Value
This is likely where you are encountering errors. Try declaring a string and assigning it to your copy value.
Dim string1 As String
string1 = TextBox2.Value
Step through your code editor with the LOCALS window open, and watch what happens to your rngCopy object when you assign a string to it.

Excel VBA automatically updating columns (Date)

I am creating a user form that does Customer Returns. I wish to have a (Status)column that will automatically update itself. It refers to the Arrival Date of the product. It works, but, when I change the system date, the status bar does not change. What do I have to do to make it update regularly? The following is the code of what ever is working.
P.S it the code works fine when entering the values. But doesn't self update
Option Explicit
Dim dDate As Date
Private Sub cbP_CodeCR_Change()
Dim row As Long
row = cbP_CodeCR.ListIndex + 2
End Sub
Private Sub Fill_My_Combo(cbo As ComboBox)
Dim wsInventory As Worksheet
Dim nLastRow As Long
Dim i As Long
Set wsInventory = Worksheets("Inventory")
nLastRow = wsInventory.Cells(Rows.Count, 1).End(xlUp).row ' Finds last row in Column 1
cbo.Clear
For i = 2 To nLastRow 'start at row 2
cbo.AddItem wsInventory.Cells(i, 1)
Next i
End Sub
Private Sub cmdCancel_Click()
Unload CustomerReturn
End Sub
Private Sub cmdEnter_Click()
Dim cust_ID As Integer
Dim prod_Code As Integer
Dim arr_date As Date
Dim stat As String
Dim status As String
Dim rowPosition As Integer
rowPosition = 1
Sheets("Customer Return").Select
Sheets("Customer Return").Cells(1, 1).Value = "Customer ID"
Sheets("Customer Return").Cells(1, 2).Value = "Product Code"
Sheets("Customer Return").Cells(1, 3).Value = "Arrival Date"
Sheets("Customer Return").Cells(1, 4).Value = "Status"
Do While (Len(Worksheets("Customer Return").Cells(rowPosition, 1).Value) <> 0)
rowPosition = rowPosition + 1
Loop
cust_ID = txtC_IDCR.Text
Sheets("Customer Return").Cells(rowPosition, 1).Value = cust_ID
prod_Code = cbP_CodeCR.Text
Sheets("Customer Return").Cells(rowPosition, 2).Value = prod_Code
arr_date = txtA_DateCR.Text
Sheets("Customer Return").Cells(rowPosition, 3).Value = arr_date
If ((arr_date - Date) <= 0) Then
Sheets("Customer Return").Cells(rowPosition, 4).Value = "Arrived"
Else
Sheets("Customer Return").Cells(rowPosition, 4).Value = "Waiting for Delivery"
End If
End Sub
Sub Recalc()
Range("C:C").Value = Format("dd/mm/yyyy")
Range("D:D").Calculate
Call StartTime
End Sub
Sub StartTime()
SchedRecalc = Now + TimeValue("00:00:10")
Application.OnTime SchedRecalc, "Recalc"
End Sub
Sub EndTime()
On Error Resume Next
Application.OnTime EarliestTime:=SchedRecalc, _
Procedure:="Recalc", Schedule:=False
End Sub
Private Sub txtA_DateCR_AfterUpdate()
With txtA_DateCR
If .Text = "" Then
.ForeColor = &HC0C0C0
.Text = "dd/mm/yyyy"
End If
End With
End Sub
Private Sub txtA_DateCR_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Exit Sub
If Mid(txtA_DateCR.Value, 4, 2) > 12 Then
MsgBox "Invalid date, make sure format is (dd/mm/yyyy)", vbCritical
txtA_DateCR.Value = vbNullString
txtA_DateCR.SetFocus
Exit Sub
End If
dDate = DateSerial(Year(Date), Month(Date), Day(Date))
txtA_DateCR.Value = Format(txtA_DateCR.Value, "dd/mm/yyyy")
dDate = txtA_DateCR.Value
End Sub
Private Sub txtA_DateCR_Enter()
With txtA_DateCR
If .Text = "dd/mm/yyyy" Then
.ForeColor = &H80000008
.Text = ""
End If
End With
End Sub
Private Sub UserForm_Initialize()
txtA_DateCR.ForeColor = &HC0C0C0
txtA_DateCR.Text = "dd/mm/yyyy"
cmdEnter.SetFocus
Fill_My_Combo Me.cbP_CodeCR
End Sub
Deeply appreciate any help if possible.
This should work in the most common scenario when time flows forward:
Create a utility module AnyNameIsGood with this code (it comes from Sean Cheshire's answer to similar question with the Recalc body adjusted)
Dim ScheduledRecalc As Date
Sub Recalc()
Sheets("Customer Return").Range("D:D").Calculate
Call StartTime
End Sub
Sub StartTime()
ScheduledRecalc = Now + TimeValue("00:00:10")
Application.OnTime ScheduledRecalc, "Recalc"
End Sub
Sub EndTime()
On Error Resume Next
Application.OnTime EarliestTime:=ScheduledRecalc, Procedure:="Recalc", Schedule:=False
End Sub
Add this code to the ThisWorkbook module to prevent unwanted behavior while closing the module:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call EndTime
End Sub
In the CustomerReturn module (the form) change your current code to
Private Sub cmdEnter_Click()
' ...
arr_date = txtA_DateCR.Text
Sheets("Customer Return").Cells(rowPosition, 3).Value = arr_date
Sheets("Customer Return").Cells(rowPosition, 3).NumberFormat = "dd\/mm\/yyyy"
Sheets("Customer Return").Cells(rowPosition, 4).FormulaR1C1 = "=IF(DAYS(R[0]C[-1],TODAY())<=0,""Arrived"",""Waiting for Delivery"")"
End Sub
It will format the date cells and it will make the generated Status formulas sensitive to the Excel's Calculate Now (F9) event.
Somewhere (e.g. in the Workbook_Open event handler) call the StartTime utility procedure (once). It will trigger automatic recalculation of the Status column.
Steps 1, 2, 4 are optional and not needed if the refresh does not have to be automatic as the end user can refresh the statuses anytime by pressing F9