setting variable as a found value produces "compile error" in vba - excel

I'm trying to set a variable based on the value I find, however VB produces "Compile error: invalid identifier", and highlights my variables. I will post code below and identify the line where the error is being produced.
What the code does:
a) Asks user to input start & end dates in the format week/year
b) If the user does that the code will find the specified value in the range and take the value which is 4 rows below that value.
That's it - pretty simple & straightforward...
Private Sub Workbook_Open()
Dim ans As Variant, stDt As Variant, endDt As Variant, endCl As Variant, stCl As Variant, wsheet As Worksheet, wbook As Workbook, _
fn_stDt As Variant, wk As Integer, rl_st_Dt As String, rl_end_Dt As String, fn_endDt As Variant
Set wbook = Workbooks("wbook1.xlsm")
Set wsheet = wbook.Worksheets("sheet1")
ans = MsgBox("Would you like to specify the range of dates now?", vbYesNo, "Select answer")
If ans = vbYes Then
stDt = Application.InputBox("Please input the starting date", "Start week for forecast / sales", "ww/yyyy", vbOKCancel, vbQuestion)
If stCl = vbCancel Then
Exit Sub
End If
endDt = Application.InputBox("Please input the end date", "End week for forecast / sales", "ww/yyyy", vbOKCancel, vbQuestion)
If endCl = vbCancel Then
Exit Sub
End If
Else
Exit Sub
End If
With wsheet.Range("S5", Range("S5").End(xlToRight))
Set fn_stDt = .Find(what:=stDt, LookIn:=xlValues, searchorder:=xlByRows, _
searchdirection:=xlNext, MatchCase:=False, searchformat:=False)
If Not fn_stDt Is Nothing Then
wk = fn_stDt.Offset(-2, 0).Value
If wk.Value <> wk.Offset(0, 1).Value Then 'Compile Error: Invalid qualifier error appears first here and highlights "wk"
rl_st_Dt.Value = wk.Offset(-4, 0).Value
ElseIf wk.Value = wk.Offset(0, 1) Then
rl_st_Dt.Value = wk.Offset(-4, 1).Value
End If
End If
End With
With wsheet.Range("S5", Range("S5").End(xlToRight))
Set fn_endDt = .Find(what:=endDt, LookIn:=xlValues, searchorder:=xlByRows, _
searchdirection:=xlNext, MatchCase:=False, searchformat:=False)
If Not fn_endDt Is Nothing Then
wk.Value = fn_endDt.Offset(-2, 0).Value
If wk.Value <> wk.Offset(0, 1).Value Then
rl_end_Dt.Value = wk.Offset(-4, 0).Value
ElseIf wk.Value = wk.Offset(0, 1).Value Then
rl_end_Dt.Value = wk.Offset(-4, 1).Value
End If
End If
End With
End Sub
Could anyone please propose a resolution to the above?
Thanks

Related

How to Find, cut, paste and erase with VBA code

I am new on VBA and i dont know almost nothing.
I've been trying a code to find a value entered in a inputbox "CXRG", find on sheet "ESTOQUEV" cut all the line and paste on sheet "SAIDA" (down from another values) and erase the blank line from "ESTOQUEV"
Someone could help me?
Private Sub CommandButton1_Enter()
linha = Worksheets("SAIDA").Range("A100000").End(xlUp).Row + 1
Worksheets("SAIDA").Cells(linha, 1) = CXOS.Value
Worksheets("SAIDA").Cells(linha, 2) = CXRG.Value
CXOS.Text = ""
CXRG.Text = ""
SendKeys "{TAB}", True ' Envia TAB para pular par o inicio.
Call refresh.Macro8
End Sub
you have to try this code (run just findAndPast())
Sub findAndPast()
Dim shttoFind As Worksheet
Dim shttoPast As Worksheet
Dim LastRowOffind As Long
Dim inBox As String
Dim cell As Range
Set shttoFind = Worksheets("ESTOQUEV")
Set shttoPast = Worksheets("SAIDA")
Call Find_Last
LastRowOffind = shttoPast.Cells(shttoPast.Rows.Count, "A").End(xlUp).Row + 1
ActiveCell.EntireRow.Copy
shttoPast.Activate
shttoPast.Cells(LastRowOffind, 1).PasteSpecial
shttoFind.Activate
ActiveCell.EntireRow.Delete
End Sub
Sub Find_Last()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
With Sheets("ESTOQUEV").Range("A:C")
Set Rng = .Find(What:=FindString, _
After:=.Cells(1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
End If
End Sub

How do I ignore no user input?

My code is supposed to check each column "C" cell for whatever input is in TextBox2 then, if found, using the row found in adjust the Column "D" intersected cell contents to "IN".
All this is happening as desired with one exception. If I click the command button "Check IN" with no input in textbox2, it sets the first next empty cell in column "D" as "IN".
Private Sub CheckIn_Click()
Dim FoundRange As Range
Dim Status As Range
Set FoundRange = Columns("C").Find(What:=TextBox2.Text, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not FoundRange Is Nothing Then
Set Status = FoundRange.Offset(ColumnOffset:=1)
Status.Value = "IN"
TextBox2 = ""
ThisWorkbook.Save
Else
Status.Value = ""
TextBox2 = ""
TextBox1.SetFocus
MsgBox "Not Found"
End If
End Sub
What I attempted to do is use the same script from line 9 at line 13 but with an empty value so that even if something is done the cell is empty. On the other hand, after running the code without TextBox2 input I received this error:"Object variable or With block variable not set" at line 13.
I do not understand what variable is not being set. All I am trying to do is mitigate what happens if the button is hit with no input.
Test First:
Private Sub CheckIn_Click()
Dim FoundRange As Range
Dim Status As Range
If TextBox2.Text = "" Then
MsgBox "Test Skipped"
Else
Set FoundRange = Columns("C").Find(What:=TextBox2.Text, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not FoundRange Is Nothing Then
Set Status = FoundRange.Offset(ColumnOffset:=1)
Status.Value = "IN"
TextBox2 = ""
ThisWorkbook.Save
Else
Status.Value = ""
TextBox2 = ""
TextBox1.SetFocus
MsgBox "Not Found"
End If
End If
End Sub
First check the value of TextBox2, then proceed if there is a value.
Private Sub CheckIn_Click()
If TextBox2.Value <> "" Then
Dim FoundRange As Range
Dim Status As Range
Set FoundRange = Columns("C").Find(What:=TextBox2.Text, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not FoundRange Is Nothing Then
Set Status = FoundRange.Offset(ColumnOffset:=1)
Status.Value = "IN"
TextBox2.Value = ""
Else
MsgBox "Not Found"
End If
End If
End Sub

Function to find all matches of a value

I need your help.
Sorry, I am really new to VBA but, how do I go about converting or adding onto the Excel function below to loop through all the found matches. Right now it only returns 1 match but i'd like to to have it modified to return all occurrences of a match so that I can input it into my userform for processing later.
Private Sub Search_Click()
With Sheet1
Set foundCell = .Cells.find(What:="test", After:=.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not foundCell Is Nothing Then
MsgBox ("""Match"" found in row " & foundCell.Row)
form1.location.Value = Cells(foundCell.Row, 1).Value
Else
MsgBox ("No match not found")
End If
End Sub
You can try findnext or add some small edits like something along these lines, just a continuous loop until you run out of matches
Private Sub Search_Click()
Dim rowNum As Long: rowNum = 1
Dim colNum As Long: colNum = 1
Do While ( True )
With Sheet1
Set foundCell = .Cells.find(What:="test", After:=.Cells(rowNum, colNum), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not foundCell Is Nothing Then
MsgBox ("""Match"" found in row " & foundCell.Row)
form1.location.Value = form1.location.Value & vbCrLf & Cells(foundCell.Row, 1).Value
if foundCell.Row < rowNum Then Exit Do
rowNum = foundCell.Row
colNum = foundCell.Column
Else
If rowNum = 1 Then MsgBox ("No matches found")
Exit Do
End If
Loop
End Sub
Just in case you need to store data for all cells that contained your search item, you could use the following. Usage: myArray = makeArrayFoundCellInfoInRange("test", Sheets.("Sheet1").Range("A1:Z500"))
'**************************************************************************************************************************************************************
'To return an array of information (value, formula, address, row, and column) for all the cells from a specified Range that have the searched item as value
'Returns an empty array if there is an error or no data
'**************************************************************************************************************************************************************
Public Function makeArrayFoundCellInfoInRange(ByVal itemSearched As Variant, ByVal aRange As Variant) As Variant
Dim cell As Range, tmpArr As Variant, x As Long
tmpArr = Array()
If TypeName(aRange) = "Range" Then
x = 0
For Each cell In aRange
If itemSearched = cell.Value Then
If x = 0 Then
ReDim tmpArr(0 To 0, 0 To 4)
Else
tmpArr = reDimPreserve(tmpArr, UBound(tmpArr, 1) + 1, UBound(tmpArr, 2))
End If
tmpArr(x, 0) = cell.Value
tmpArr(x, 1) = cell.Formula
tmpArr(x, 2) = cell.Address(0, 0) 'Without the dollar signs
tmpArr(x, 3) = cell.Row
tmpArr(x, 4) = cell.Column
x = x + 1
End If
Next cell
End If
makeArrayFoundCellInfoInRange = tmpArr
Erase tmpArr
End Function

Deleting entire rows

My question is, why whenever I try to debug the error is
Runtime error 91; Object variable or with block variable not set.
I try to look at another example and try to find the solution in the forum but still, I cannot find it.
Btw, when I debug it will highlight at
findvalue.EntireRow.Delete
May I know what is the error ya? Hopefully, there is someone can explain it to me.
Thank you.
Private Sub cmdDelete_Click()
Dim findvalue As Range
Dim cDelete As VbMsgBoxResult
Dim cNum As Integer
Dim DataSH As Worksheet
Set DataSH = Sheet1
Dim x As Integer
Application.ScreenUpdating = False
If Emp1.Value = "" Or Emp2.Value = "" Then
MsgBox "There is not data to delete"
Exit Sub
End If
cDelete = MsgBox("Are you sure that you want to delete this training", _
vbYesNo + vbDefaultButton2, "Are you sure????")
If cDelete = vbYes Then
Set findvalue = DataSH.Range("B:B").Find(What:=Me.Emp1.Value, _
LookIn:=xlValues, LookAt:=xlWhole)
findvalue.EntireRow.Delete
End If
cNum = 7
For x = 1 To cNum
Me.Controls("Emp" & x).Value = ""
Next
DataSH.Range("A2").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Range("Data!$L$8:$L$9"), CopyToRange:=Range("Data!$N$8:$T$8"), _
Unique:=False
If DataSH.Range("N9").Value = "" Then
lstEmployee.RowSource = ""
Else
lstEmployee.RowSource = DataSH.Range("outdata").Address(external:=True)
End If
DataSH.Select
With DataSH
.Range("A2:G10000").Sort Key1:=Range("E2"), Order1:=xlAscending, Header:=xlGuess
End With
Sheet1.Select
On Error GoTo 0
Exit Sub
End Sub
You simply aren't finding the value from Me.Emp1.Value in column B of the Data worksheet so there is Nothing to delete. Maybe expand the Find arguments; matchcase:=false comes to mind.
Error controlled:
Set findvalue = DataSH.Range("B:B").Find(What:=Me.Emp1.Value, _
LookIn:=xlValues, LookAt:=xlWhole)
if not findvalue is nothing then findvalue.EntireRow.Delete
Alternate:
dim m as string
m = application.match(Me.Emp1.Value, DataSH.Range("B:B"), 0)
if not iserror(m) then DataSH.rows(m).entirerow.delete
Additional AdvancedFilter range definitions:
with DataSH
.Range("A2").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=.Range("L8:L9"), CopyToRange:=.Range("N8:T8"), _
Unique:=False
end with

Search for a string in a Worksheet using VBA

I am trying to search for a particular string "ERROR" in all the worksheets in the workbook and make it bold and color the found cell red.
I am able to parse through each worksheet. I am not able to use the Find function of VBA.
Here's an example of using Find and formatting the found cells
Sub FindERROR()
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim FirstFound As String
Dim sh As Worksheet
' Set Search value
SearchString = "ERROR"
Application.FindFormat.Clear
' loop through all sheets
For Each sh In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = sh.Cells.Find(What:=SearchString, _
After:=sh.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
FirstFound = cl.Address
' format found cell
Do
cl.Font.Bold = True
cl.Interior.ColorIndex = 3
' find next instance
Set cl = sh.Cells.FindNext(After:=cl)
' repeat until back where we started
Loop Until FirstFound = cl.Address
End If
Next
End Sub
if you are searching in excel vba you can use following simple code with InStr command.
Private Sub CommandButton1_Click()
Dim RowNum As Long
RowNum = 1
Do Until Sheets("Data").Cells(RowNum, 1).Value = ""
If InStr(1, Sheets("Data").Cells(RowNum, 2).Value, TextBox1.Value, vbTextCompare) > 0 Then
On erro GoTo next1
ListBox1.AddItem Sheets("Data").Cells(RowNum, 1).Value
ListBox1.List(ListBox1.ListCount - 1, 1) = Sheets("Data").Cells(RowNum, 2).Value
End If
next1:
RowNum = RowNum + 1
Loop
End Sub
you can download example file from here
How about this:
If Not WorkBook.Sheets("Sheet1").Range("A1:Z150").Find("Cookie") Is Nothing
MsgBox "Found a Cookie"
End If

Resources