Walking Through Flagged Cells Individually - vba

I have a stretch goal for my project that goes way beyond my current ability, but I was hoping someone here could put me on the right track. I have the following code:
Public ErrorCount As Integer
Sub GeneralFormat()
ErrorCount = 0
VLookup
MacroFillAreas
color
NonZeroCompare
MustBe
MsgBox ("Number of Errors" & CStr(ErrorCount))
End Sub
I also have the following section of the code:
Sub NonZeroCompare()
Dim i As Long
For i = 5 To 1000 Step 1
If Range("AK" & i).Value = "On" Then
If Range("AL" & i).Value = 0 And Range("AM" & i).Value = 0 Then
Range("AL" & i, "AM" & i).Interior.ColorIndex = 6
ErrorCount = ErrorCount + 1
End If
ElseIf Range("BC" & i).Value = 0 And Range("BD" & i).Value = 0 Then
Range("BC" & i, "BD" & i).Interior.ColorIndex = 6
ErrorCount = ErrorCount + 1
ElseIf Range("EJ" & i).Value = "On" Then
If Range("EK" & i).Value = 0 And Range("EL" & i).Value = 0 Then
Range("EK" & i, "EL" & i).Interior.ColorIndex = 6
ErrorCount = ErrorCount + 1
End If
ElseIf Range("ES" & i).Value = 0 And Range("ET" & i).Value = 0 Then
Range("ES" & i, "ET" & i).Interior.ColorIndex = 6
ErrorCount = ErrorCount + 1
ElseIf Range("FG" & i).Value = 0 And Range("FH" & i).Value = 0 Then
Range("FG" & i, "FH" & i).Interior.ColorIndex = 6
ErrorCount = ErrorCount + 1
End If
Next i
End Sub
My desired effect is to have the user be able to jump to each cell that contributes to "ErrorCount". There are thousands of cells in my workbook to manage, so being able to jump to the error on review would be great. It would be even better if it could be done with one key on the keyboard, but a button would work too.
Any ideas on how to execute something like this? Also, difficulty level? Any resources on where to begin on this type of feature? Last question: Any native features to excel that I can code in to use that won't require hardcore coding?

Here's an approach that could work in your to handle your requirements.
First, instead of holding only a count of the number of errors, we can hold a Dictionary object that holds references to the cell locations. Using this object, we can then inspect it for a total count of errors, locations, etc.
I'm going to show one (relatively simple) implementation below. (If you're unfamiliar with Dictionary objects, do some research. Basically, it holds a unique key and a corresponding value). In my case, I chose to store the address of an error cell as the key, and I just stored a blank string as the value.
First, I wrote a function to return the dictionary object holding the errors. In the simple implementation, I had a fixed range, and I stored in the address of any cell that had text 'Abc'.
Next, I wrote a helper function that returns a count of the number of objects (this is simple enough that you don't really need a helper function, but it might simplify things if making multiple calls or if you will add more customized logic).
Finally, two subroutines accomplish the final req: traversing through the errors. The first routine 'TraverseErrorsgoes through the dictionary and "visits" each of the addresses. This then yields to aDoEventscall which allows the user to do what they need to. TheJumpAhead` routine tells the system that the user is all finished.
It is helpful to attach a keyboard shortcut to the JumpAhead method. To do so, while in the Excel workbook, press ALT + F8 to open up the macro window. Select the JumpAhead routine, then click the Options button in the dialog box. This allows you to enter a letter that when pressed along with the CTRL key, runs the macro. (I selected the letter e, so CTRL + e allows me to jump ahead once I've made the changes).
There are some challenges to consider. For example, my cell addresses do NOT have a reference sheet. Therefore, if this macro switches worksheets, you may run into some trouble.
Let me know of any questions.
Dim oDictCellsWithErrors As Object
Dim bContinue As Boolean
Private Function GetErrorsDict() As Object
Dim rData As Range
Dim rIterator As Range
'This helper function returns the dictionary object containing the errors
'If it's already been populated
'If not, it creates then returns the object
If Not oDictCellsWithErrors Is Nothing Then
Set GetErrorsDict = oDictCellsWithErrors
Exit Function
End If
'Some logic to create a dictionary of errors
'In my case, I'm adding all cells that have the text "Abc"
'Your logic should differ
Set rData = Sheet1.Range("A2:A15")
Set oDictCellsWithErrors = CreateObject("Scripting.Dictionary")
For Each rIterator In rData
If rIterator.Value = "Abc" Then
If Not oDictCellsWithErrors.exists(rIterator.Address) Then
oDictCellsWithErrors(rIterator.Address) = ""
End If
End If
Next rIterator
Set GetErrorsDict = oDictCellsWithErrors
End Function
Private Function CountErrors() As Integer
'This function returns the number of errors in the document
CountErrors = GetErrorsDict().Count
End Function
Sub TraverseErrors()
Dim oDict As Object
Dim sKey As Variant
Set oDict = GetErrorsDict()
For Each sKey In oDict.keys
bContinue = False
Sheet1.Range(sKey).Activate
Do Until bContinue
DoEvents
Loop
Next sKey
MsgBox "No more errors"
End Sub
Sub JumpAhead()
bContinue = True
End Sub

Related

RunTime Error 13, Type Mismatch MsgBox Cancel

Getting a Run-Time Error 13 type mistmatch error when clicking cancel on a message box.
I tried making the following script to handle if a message box is empty, however upon bug checking, clicking cancel on the message box throws it all out.
Any ideas?
Private Sub ChangeDebtAmounts_Click()
Dim Debt1 As Integer, Debt2 As Integer, Debt3 As Integer, Debt4 As Integer
Dim D1Range As String, D2Range As String, D3Range As String, D4Range As String
D1Range = ActiveSheet.Range("Y15")
D2Range = ActiveSheet.Range("Y16")
D3Range = ActiveSheet.Range("Y17")
D4Range = ActiveSheet.Range("Y18")
Debt1 = InputBox("Please Enter in the account limit for " & D1Range)
If Debt1 = "" Then
MsgBox ("Setting " & D1Range & " to Zero, No Value Entered")
Else
Range("AA15").Value = Debt1 - Range("S58")
End If
End
End Sub
The type mismatch is with the InputBox rather than the MsgBox. To fix it, it is enough to change Dim Debt1 As Integer to Dim Debt1 As Variant. Also, you are using MsgBox as a sub rather than a function so the correct syntax should be
MsgBox "Setting " & D1Range & " to Zero, No Value Entered"
rather than
MsgBox ("Setting " & D1Range & " to Zero, No Value Entered")
In this case the parentheses are harmless, but if you try to give additional arguments to MsgBox while using it as a sub then you will get a syntax error.
Here's a slightly different take on your question. See my comments within the code.
(It's longer just because of the comments; optionally, you can remove any lines of comments, as well as any other blank lines.)
Private Sub ChangeDebtAmounts_Click()
Dim Debt1, Debt2, Debt3, Debt4 'data type "Variant" is assumed
Dim D1Range As String,D2Range As String,D3Range As String,D4Range As String
'by using a "With" statement, you can use "." instead of "ActiveSheet."
With ActiveSheet
D1Range = .Range("Y15")
D2Range = .Range("Y16")
D3Range = .Range("Y17")
D4Range = .Range("Y18")
'I added a title to the dialog and a default value of zero
Debt1=InputBox("Enter the account limit for " & D1Range, "Limit?" ,0)
'Check user response:
If Debt1 = "" Or Debt1 = 0 Then
'User clicked cancel or entered zero.
MsgBox "Setting " & D1Range & " to Zero, No Value Entered"
'I assume your next step is to set the input value to zero:
Debt1 = 0
Else
'you don't need to specify ".Value" in most cases (it's assumed)
'also:by using the "." we're referring to ActiveSheet again.
.Range("AA15") = Debt1 - .Range("S58")
End If
End With '(the end of "With ActiveSheet")
End Sub
A couple other thoughts:
it appears like you're going to use different variables for each InputBox but this is not necessary: you can re-use the same variable in this case, without issue.
ActiveSheet just refers to "whichever worksheet (tab) happens to be open when the code is run". It's a good idea to explicitly refer to a specific worksheet, to prevent potential problems in the future.
For example if your cells such as Y15 are on worksheet Sheet1, you could replace ActiveSheet with Sheets("Sheet1").
Alternate method (loop through all 4 cells)
These methods are for demonstration only - if you already have your solution figured out, stick with that, there's no point in wasting time! These are just to show other ways to do the same thing.
Just for fun, here's another alternate method, that loops through all 4 cells Y15:Y18 and repeats the same MsgBox's.
I wasn't sure what happens with the other 3 values the user enters, so I left those blank.
Private Sub demo_Alternate()
Dim userInput As Variant, arr As Variant, myCell
With Sheets("Sheet1") '<<<<<< change this to actual worksheet name
arr = .Range("Y15:Y18") ' arr(1) to arr(4) are now cell references
For Each myCell In arr
userInput = InputBox("Enter account limit for " & myCell, "Limit?", 0)
If userInput = "" Or userInput = 0 Then 'Cancelled or 0 entered
MsgBox "Setting " & myCell & " to Zero, No Value Entered"
userInput = 0
Else
Select Case Split(myCell.Address, "$")(2)
Case 15 'do what you need to for cell Y15
Range("AA15") = userInput - Range("S58")
Case 16
'do what you need to for cell Y16
Case 17
'do what you need to for cell Y16
Case 18
'do what you need to for cell Y16
End Select
End If
Next myCell 'loop to next cell
End With
End Sub
OR, if all four cells are getting from S58 and put into column AA of the same row, like:
...if your end-goal is the pattern:
AA15 = {Y15 or UserEntry} - S58
AA16 = {Y16 or UserEntry} - S58
AA17 = {Y17 or UserEntry} - S58
AA18 = {Y18 or UserEntry} - S58
...then something like this could work (and is even more compact).
Private Sub demo_Alternate2()
Dim userInput As Variant, arr As Variant, myCell, rowNum As Long
With Sheets("Sheet1") '<<<<<<<<<<<<< change this to actual worksheet name
arr = .Range("Y15:Y18") ' arr(1) to arr(4) are now cell references
For Each myCell In arr
userInput = InputBox("Enter account limit for " & myCell, "Limit?", 0)
If userInput = "" Or userInput = 0 Then 'Cancelled or 0 entered
MsgBox "Setting " & myCell & " to Zero, No Value Entered"
Else
rowNum = Split(myCell.Address, "$")(2)
Range("AA" & rowNum) = userInput - Range("S58")
End If
Next myCell
End With
End Sub
One noteworthy technique used here is the use of an array (arr) to read multiple cell values at once instead of a separate line for each cell input.
arr = .Range("Y15:Y18")
...assigns the four cells to the array so you can refer to the array as if:
arr(1) = Y15
arr(2) = Y16
arr(3) = Y17
arr(4) = Y18

VBA Powerpoint Reference a textbox with variable

I am attempting to write a vba loop that will detect the value of all ActiveX textboxes on the slide. However I am have trouble writing the code for the "variable" in the textbox reference. For example TextBox(i) needs to be referenced in the loop. Where i is an integer I set the value to.
Dim i as Integer
For i = 1 to 4
If IsNull(Slide1.Shapes.("TextBox" & i).Value) = True
Then (Slide1.Shapes.("TextBox" & i).Value) = 0
Else: ...
Next i
However this script doesn't work and I have been unable to locate a source for how to properly code this variable portion of script. There has been some talk of using Me.Controls however I am not creating a form. Would anyone be willing to share what the error is here in my script?
This will put the value of i into TextBox i. Should get you started, I think.
Sub Example()
Dim oSh As Shape
Dim i As Integer
On Error Resume Next
For i = 1 To 4
Set oSh = ActivePresentation.Slides(1).Shapes("TextBox" & CStr(i))
If Err.Number = 0 Then ' shape exists
oSh.OLEFormat.Object.Text = CStr(i)
End If
Next i
End Sub
#Steve Rindsberg you had the correct code. Thank you. Here was the final script to obtain the value, and set the value if blank.
For i = 1 To 4
'set oSh to TextBox1, TextBox2, TextBox3... etc.
Set oSh = ActivePresentation.Slides(1).Shapes("TextBox" & CStr(i))
'set myVar to value of this TextBox1, TextBox2...
myVar = oSh.OLEFormat.Object.Value
If myVar = "" Then _
ActivePresentation.Slides(1).Shapes("Text" & CStr(i)).OLEFormat.Object.Value = 0 _
Else: 'do nothing
'clear value of myVar
myVar = ""
'start on next integer of i
Next i

VBA Textbox value loop vlookup for number of times value is found

I am creating a table in my spreadsheet that contains categories, questions and answers for a quiz.
The user is presented with a form, allowing them to navigate around the workbook easily, this also includes a textbox option, allowing them to search for a phrase if they are unsure what category the question/answer may fall into.
I have generated a vlook up to pull from the table of categories/questions and answers to the user on a different worksheet.
I have also generated a count, so I am able to identify how many times this work appears across the quiz table.
My problem is I am struggling to develop a loop so that if the key phrase is found 6 times for example, i want 6 questions and answers to be listed to the user. Currently it is only pulling the final time it is found.
My current code includes the following:
Private Sub CommandButton1_Click()
If Len(search_text) = 0 Then
MsgBox "Please enter a key word to search for!", vbCritical
End If
Dim wordCount As Integer
wordCount = Application.WorksheetFunction.CountIf(Sheet1.Range("A2:c600"), "*" & search_text.Value & "*")
'Else: wordCount = WorksheetFunction.CountIf(Sheet1.Range("A2:c600"), search_text.Value)
If wordCount = 0 Then
MsgBox "No match found"
Else
Sheet2.Range("a7").Value = WorksheetFunction.VLookup("*" & search_text.Value & "*", Sheet1.Range("A2:c600"), 3, False)
Sheet2.Range("b7") = wordCount
End If
End Sub
Any advice on implementing a loop and to allow the question/answer to be printed one after another would be very much appreciated.
I have read many other question pages about this and none seem to match what I am trying to do.
Many thanks in advance
I use a combination of Find and FindNext to search through a range of cells for the term entered in the search_text input field. I added comments to my code to better help you understand what exactly is going on.
I don't know exactly what you need to do with the results when you find them, for now I just display a message box showing the match. We can work on what to actually do with the results if you want to clarify in the comments what exactly you want.
This code assumes you have a worksheet named Results
Private Sub CommandButton1_Click()
Dim rngResult As Range
Dim strFirstAddress As String
Dim i As Long
If Len(search_text.Text) = 0 Then
MsgBox "Please enter a key word to search for!", _
vbCritical
'Stop code exeuction if no search
'term is entered
Exit Sub
End If
'Clear the previous results range
Sheets("Results").Range("A2:C600").ClearContents
'Set i to row 2 of the results worksheet
i = 2
'Look in range A2:C600 of Sheet1
With Sheet1.Range("A2:C600")
'Perform the initial find
Set rngResult = .Find(What:=search_text.Text, LookAt:=xlPart)
'Check to ensure that the term is found
If Not rngResult Is Nothing Then
'Grab the cell address of the first match
'This will help to avoid an infinite loop
strFirstAddress = rngResult.Address
'Continue Searching
Do
'Display the output to you
'MsgBox "Matched '" & search_text.Text & "' to " & rngResult.Value & " in cell " & rngResult.Address
'Put the result on the results page
Sheets("Results").Range("A" & i & ":C" & i).Value = Range("A" & rngResult.Row & ":C" & rngResult.Row).Value
i = i + 1
'Move on to the next result
Set rngResult = .FindNext(rngResult)
'Break out of the loop when we return to the starting point of the search
Loop While Not rngResult Is Nothing And rngResult.Address <> strFirstAddress
End If
End With
'Clean up variables
Set rngResult = Nothing
End Sub

Efficiently transfer Excel formatting data to text file

Here it is, I have a huge Excel workbook with which users write pricing quotes. On save, rather than saving the huge workbook, I'm transferring the relevant data to a text file and saving that text file. It's going off without a hitch, except for the one worksheet that contains formatting. I don't want the user to lose formatting when they load the previously saved quote (from the text file), so I need to determine a way to transfer that formatting data to and from the text file. Is there a smart way to do this without writing hundreds of lines of code or using any non-native Excel feature?
Here's a sample of the code for other sheets, but it's not much help for what I'm trying to do:
Sub WriteQuote()
Dim SourceFile As String
Dim data As String
Dim ToFile As Integer
Dim sh1, sh2, sh3 As Worksheet
Set sh1 = Sheets("sheet 1")
Set sh2 = Sheets("sheet 2")
Set sh3 = Sheets("sheet 3")
SourceFile = "C:\Users\███████\Desktop\test.txt"
ToFile = FreeFile
Open SourceFile For Output As #ToFile
'PRINT DETAILS TO TXT FILE
For i = 7 To 56
If sh1.Range("B" & i).Value <> "" Then
data = sh1.Range("B" & i).Value & "__"
If sh1.Range("D" & i).Value <> "" Then
data = data & sh1.Range("D" & i).Value & "__"
Else: data = data & " __"
End If
If sh1.Range("E" & i).Value <> "" Then
data = data & "ns" & "__"
Else: data = data & " __"
End If
data = data & sh1.Range("F" & i).Value & "__"
data = data & sh1.Range("G" & i).Value & "__"
data = data & sh1.Range("J" & i).Value & "__"
data = data & sh1.Range("M" & i).Value
Else: Exit For
End If
Print #ToFile, data
Next i
Close #ToFile
End Sub
This is an example using a user type ("record") and Random access IO.
There are limitations, and I believe using Random access
would probably waste space on disk, however it is a reasonable
way to go about doing this.
In the example I suggest using a bit mask for boolean properties,
for example "Bold" (a bit mask can save space and shorten the code).
The file read/write actions are based on :
https://support.microsoft.com/en-us/kb/150700
!!! It is possible that you'll get a "bad record length" error, although
every this is fine and works the first time. There are allot of reports about this issue (google VBA bad record length). If that is the case, you might want to change the IO to Binary instead of Random (code change will be needed).
!!!!! Add a module and paste the code there, or, for the very least,
paste the record in a module (not in a sheet).
Option Explicit
' Setting up a user type ("record").
' you can add more variables, however just makes sure they are fixed
' length, for example: integer\doube\byte\... Note that if you want to
' add a string, ' make sure to give it fixed length, as shown below.
Public Type OneCellRec
' this will hold the row of the source cell
lRow As Long
' this will hold the column of the source cell
lColumn As Long
' This will hold the value of the cell.
' 12 is the maximum length you expect a cell to have-
' CHANGE it as you see fit
Value As String * 12
' This hold the number format- again, you might need to
' twik the 21 length-
NumberFormat As String * 21
' will hold design values like Bold, Italic and so on
DesignBitMask1 As Integer
' will hold whether the cells has an underline- this is not boolean,
' as there are several type of underlines available.
UnderLine As Long
FontSize As Double
End Type
' ---- RUN THIS ---
Public Sub TestFullTransferUsingRec()
Dim cellSetUp As Range
Dim cellSrc As Range
Dim cellDst As Range
Dim r As OneCellRec
Dim r2 As OneCellRec
On Error Resume Next
Kill "c:\file1.txt"
On Error GoTo 0
On Error GoTo errHandle
' For the example,
' Entering a value with some design values into a cell in the sheet.
' --------------------------------------
Set cellSetUp = ActiveSheet.Range("A1")
cellSetUp.Value = 1.5
cellSetUp.Font.Bold = True
cellSetUp.Font.Size = 15
cellSetUp.Font.UnderLine = xlUnderlineStyleSingle
cellSetUp.NumberFormat = "$#,##0.00"
' Doing it again for example purposes, in a different cell.
Set cellSetUp = ActiveSheet.Range("C5")
cellSetUp.Value = "banana"
cellSetUp.Font.Bold = True
cellSetUp.Font.Size = 15
cellSetUp.Font.UnderLine = XlUnderlineStyle.xlUnderlineStyleDouble
' ============ saving the cells to the text file =============
' open file for write
Open "c:\file1.txt" For Random As #1 Len = Len(r)
' save to a record the value and the design of the cell
Set cellSrc = ActiveSheet.Range("A1")
r = MyEncode(cellSrc)
Put #1, , r
' save to a record the value and the design of the cell
Set cellSrc = ActiveSheet.Range("C5")
r = MyEncode(cellSrc)
Put #1, , r
Close #1
' ============ loading the cells from the text file =============
Application.EnableEvents = False
' open file for read
Dim i%
Open "c:\file1.txt" For Random As #1 Len = Len(r2)
' read the file
For i = 1 To Int(LOF(1) / Len(r))
Get #1, i, r2
' destination cell- write the value and design
' --------------------------------------------
Set cellDst = Sheet2.Cells(r2.lRow, r2.lColumn)
Call MyDecode(cellDst, r2)
Next
'Close the file.
Close #1
errHandle:
If Err.Number <> 0 Then
MsgBox "Error: " & Err.Number & " " & _
Err.Description, vbExclamation, "Error"
On Error Resume Next
Close #1
On Error GoTo 0
End If
Application.EnableEvents = True
End Sub
' Gets a single cell- extracts the info you want into a record.
Public Function MyEncode(cell As Range) As OneCellRec
Dim r As OneCellRec
Dim i%
i = 0
r.lRow = cell.row
r.lColumn = cell.column
r.Value = cell.Value
r.FontSize = cell.Font.Size
r.UnderLine = cell.Font.UnderLine
r.NumberFormat = cell.NumberFormat
' Use a bit mask to encode true\false excel properties.
' the encode is done using "Or"
If cell.Font.Bold = True Then i = i Or 1
If cell.Font.Italic = True Then i = i Or 2
'If cell. ..... .. = True Then i = i Or 4
'If cell. ..... .. = True Then i = i Or 8
'If cell. ..... .. = True Then i = i Or 16
'If cell. ..... .. = True Then i = i Or 32
'If cell. ..... .. = True Then i = i Or 64
'If cell. ..... .. = True Then i = i Or 128
'If cell. ..... .. = True Then i = i Or 256
' Remember the Integer limit. If you want more than int can handle,
' use long type for the i variable and r.DesignBitMask1 variable.
'If cell. ..... .. = True Then i = i Or ' (2^x)-
r.DesignBitMask1 = i
MyEncode = r
End Function
' Decode- write the info from a rec to a destination cell
Public Sub MyDecode(cell As Range, _
r As OneCellRec)
Dim i%
cell.Value = r.Value
i = r.DesignBitMask1
cell.Value = Trim(r.Value)
cell.Font.Size = r.FontSize
cell.Font.UnderLine = r.UnderLine
' trim is important here
cell.NumberFormat = Trim(r.NumberFormat)
' Use a bit mask to decode true\false excel properties.
' the decode is done using "And"
If i And 1 Then cell.Font.Bold = True
If i And 2 Then cell.Font.Italic = True
'If i And 4 Then ...
'If i And 8 Then ...
'...
End Sub
You could try TextToColumns. You're writing a delimiter in "__" that you could take advantage of. It also seems to keep the formatting of the cells when receiving the parsed text.
Sub ReadQuote()
SourceFile = "C:\Users\||||||\Desktop\test.txt"
Open SourceFile For Input As #8
Input #8, data
Range("M1") = data 'Temporary holder for an input line
'Range to start the parsed data "A1" in this example
Range("A1") = Range("M1").TextToColumns(, xlDelimited, , , , , , , , "__")
Close #8
End Sub

VB get data from excel - validation

I have a code which is mainly working except I have a validation error...
My code has a search box where I put the surname in, the idea is that if the surname entered is in the excel sheet and a bunch of information is returned. This works as desired, as does my validation for no data entered in the search box.
What doesn't work is my validation for when I enter something in the search box which isn't a match (i.e. not in the excel sheet). Please see 'match validation' in the following code to see what I'm referring to do.
I just have no idea why it isn't working. I don't even get an error when I run the code and enter in wrong data, it just doesn't return an error message like it should and the form sort of freezes up (kinda like its in a non stop loop).
Any advice would be great, Thanks! Here some of the code:
'define objects
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Open a existing workbook and sheet in excel
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(Filename:="c:\users\timothy\desktop\coding\output.xlsx")
oSheet = oBook.Worksheets(1)
Dim getSurname As String = ""
Dim getFirstname As String = ""
Dim getAge As String = ""
Dim getGender As String = ""
Dim getNum As Integer = 1
Dim getValidate As Integer = 0
While oBook.Worksheets(1).Range("A" & getNum).value <> searchInput.Text.ToUpper
getNum = getNum + 1
End While
'Length Validation (THIS WORKS)
If Len(searchInput.Text) = 0 Then
getValidate = getValidate + 1
End If
'Match validation (THIS DOES NOT WORK)
If oBook.Worksheets(1).Range("A" & getNum).value <> searchInput.Text.ToUpper Then
getValidate = getValidate + 1
End If
If getValidate = 0 Then
getSurname = oSheet.Range("A" & getNum).Value.ToString
getFirstname = oSheet.Range("B" & getNum).Value.ToString
getAge = oSheet.Range("C" & getNum).Value.ToString
getGender = oSheet.Range("D" & getNum).Value.ToString
outputData.Text = "SURNAME: " & getSurname & vbCrLf & "FIRSTNAME: " & getFirstname & vbCrLf & "AGE: " & getAge & vbCrLf & "GENDER: " & getGender & vbCrLf
Else
MsgBox("ERROR!! Please enter valid Quote Number.")
End If
This section of code
While oBook.Worksheets(1).Range("A" & getNum).value <> searchInput.Text.ToUpper
getNum = getNum + 1
End While
will continue to loop through the worksheet until it finds a match. Let's assume you get to the last row of your data with no match yet. The next "A" & getNum will be blank, which will not be a match, and so it will continue the While, until it hits your row limit and errors out. It never finds a match, so it will never hit your check.
However, I think if you put a check in there to look for those blank cells...
While oBook.Worksheets(1).Range("A" & getNum).value <> searchInput.Text.ToUpper
if oBook.Worksheets(1).Range("A" & getNum).value = "" then
exit while
else
getNum = getNum + 1
end if
End While
,then I think it will do what you are looking to do.
I think that if you are going to work on really big spread sheets, you are going to run into trouble looping. Can you not rather use Find?
See: http://www.vbforums.com/showthread.php?634644-Excel-Find-Method-in-Excel-VBA-(Any-version-of-Excel)
See Down bottom (using find as vlookup)