Skip to content

Instantly share code, notes, and snippets.

@rclayton-the-terrible
Created May 15, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rclayton-the-terrible/060076910d7d35b9554b to your computer and use it in GitHub Desktop.
Save rclayton-the-terrible/060076910d7d35b9554b to your computer and use it in GitHub Desktop.
Example of locating a cell and populating values from a combo box
Private Sub btnSubmit_Click()
Dim found As Boolean
found = False
Dim i As Integer
' Start at the second cell
i = 2
' While Combo box value does not match the target cell's value or as long as the cell has a value
Do
' Bump the cell index position
i = i + 1
MsgBox Cells(i, 1).Value & " = " & cbUnitNo.Value
' Set a marker to make sure we actually found a match
' "CStr" converts the value to a String. I had to do this because
' I think Excel is automatically converting the cell or combo box
' value to a integer.
If CStr(Cells(i, 1).Value) = CStr(cbUnitNo.Value) Then
' We've found the match, set to true
found = True
End If
Loop Until CStr(Cells(i, 1).Value) = CStr(cbUnitNo.Value) Or Cells(i, 1).Value = ""
' If we've found the value in the Unit No. column
If found Then
' Set the appropriate column values. Notice I'm just using "i", my index in the loop
' as the row index.
Cells(i, 2).Value = tbMeterReading.Value
Cells(i, 3).Value = tbDate.Value
' Hide the form...or whatever you want.
Me.Hide
' If you can't find a match (probably because someone mistyped a unit number)
Else
' Pop a message box to tell them there was a problem.
MsgBox "Could not find the Unit Number in the spreadsheet"
End If
End Sub
' Dynamically initialize the combo box
Private Sub UserForm_Initialize()
Dim i As Integer
' Start at the second cell
i = 2
' Iterate over the cells in column A (e.g. "1") as long as the value is not empty
Do While Cells(i, 1).Value <> ""
' Populate the cell value in the combo box
cbUnitNo.AddItem Cells(i, 1).Value
i = i + 1
Loop
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment