Excel VBA: If Equal Not to, then show error message - excel

Can't figure out what's wrong with the code.
I have a code where I need to check if in certain sheet can be found certain products' ID before making an order.
Private Sub Pardot_Click()
Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim valueToFind As String
valueToFind = pardID
Set xlSheet = ActiveWorkbook.Worksheets("Noliktava")
Set xlRange = xlSheet.Range("A1:A500")
For Each xlCell In xlRange
If xlCell.Value <> valueToFind Then
MsgBox ("This product wasn't found in the database - ID: " & pardID.Text)
Exit Sub
End If
Next xlCell
End Sub
Basically, I launch the userform and type in the ID (i.e. 1) in the box and click "Okay" or whatever, if the ID can't be found in the range (ID:1) I want it to show the error Msg.
Code works if I change <> to =, but that's not the needed result.

Without changing your code too much, and probably saving some time, instead of checking each cell in the range, just use CountIf()?
Private Sub Pardot_Click()
Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim valueToFind As String
valueToFind = pardID
Set xlSheet = ActiveWorkbook.Worksheets("Noliktava")
Set xlRange = xlSheet.Range("A1:A500")
If WorksheetFunction.CountIf(xlRange,valuetoFind) = 0 then
msgbox "This product wasn't found in the database - ID: " & parId.textEnd
End If
End Sub
Note: this will look for exactly the text the user inserted. Use wildcards if it can be somewhere in a string (i.e. search for "dog" in "doggone", "dog food","dog")

Related

Input box to search for userform record and then delete from worksheet?

trying to figure out an easy way for when someone needs to delete their record from userform data in a spreadsheet. ideally, I want to have the user open up the userform, click delete entry and then an input box would pop up for them to type in their user ID and then the userform would search for that row in the table and delete the entry.
here is a shell of what I'm trying to accomplish:
Option Explicit
Public Sub deleteData(rngColumn As Range, strSelector As String)
Dim rngCell As Range
Dim rngToDelete As Range
Set strSelector = InputBox("Enter Employee ID")
Set rngColumn = ThisWorkbook.Worksheets("Data").Columns(3)
For Each rngCell In rngColumn
If rngCell.Value = strSelector Then
If rngToDelete Is Nothing Then
Set rngToDelete = rngCell
Else
Set rngToDelete = Union(rngToDelete, rngCell)
End If
End If
Next
If Not rngToDelete Is Nothing Then
rngToDelete.EntireRow.Select
End If
End Sub
But it's not doing anything when I try to click the button
Here is a simple code to find a user's input and delete the row.
To add the macro, double-clicking on the UserForm button in design mode will automatically create the Click event. Insert this code in the code window.
'Assign the worksheet variable
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Data")
'Assign the InputBox search string variable
Dim srchID As String: srchID = InputBox("Enter Employee ID")
'Assign a range variable to the cell where the search string is found
Dim trgtCel As Range: Set trgtCel = ws.Range("C:C").Find(What:=srchID, LookIn:=xlValues, lookat:=xlWhole)
'Delete the trgtCel row containing the Employee's Information
trgtCel.EntireRow.Delete

Getting "Subscript out of Range" Error on Vlookup

I am making a vlookup code that shows the user description when they scan item barcode but I am getting subscript out of range error
Dim ws As Worksheet
Set ws = Sheets("CONVERSION")
Dim itemcode As String
Dim description As String
Dim myrange As Range
ws.Activate
Set myrange = Range("A:B")
description = ws.Application.WorksheetFunction.VLookup(TextBox1.Value, Worksheets("CONVERSION").Range("myrange"), 2, False)
Label5 = description
Then it is supposed to assign the value of the vlookup (description) to the label
This should help:
Option Explicit
Sub Test()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("CONVERSION") 'if you don't define the workbook it will be the activeworkbook
Dim itemcode As String
Dim description As Variant 'Defining it as variant won't rise an Error if the item is not found
Dim myrange As Range
Set myrange = ws.Range("A:B") 'If you define a worksheet, you can refer to it and you won't need .Select or .Activate
description = Application.VLookup(TextBox1.Value, myrange, 2, False) 'as before, once you defined your range you can simply refer to it
If Not IsError(description) Then
Label5 = description
Else 'if nothing is found description will be an error
Label5 = "Item not found"
End If
End Sub
Application.VLookUp instead using the WorksheetFunction will prevent VBA to rise an error in case nothing is found when it's applied to a Variant so you can use that little trick to later do the if I've posted you in case your BarCode isn't yet on your database.
Ok Finaly Fixed the Problem , not the way i originaly thought but it does the job , i stopped using vlookup and did this
Dim Found As Range
Dim str As String
str = Me.TextBox1.Text
Set Found = Sheet2.Range("A2", Range("A" & Rows.Count).End(xlUp)).Find(str)
If Found Is Nothing Then
Label5 = "Not Found"
Else
Label5 = Cells(Found.Row, 2).Value
End If
i found the solution here

I need to skip empty cells in my vba button and open when is not empty

I have a button which opens a query of links whenever I click on it, however sometimes a field in my query is empty and I need my code to keep going and skip the empty cell, how can I solve that
I've already tried IsEmpty and couldn't reach the expected resultl. VBA world is quite new for me, so if you spot any silly mistake or not optimized method warn me. The code down here is from before I tried to skip the empty cells
Private Sub CommandButton1_Click()
Dim SelecRng As Range
Set SelecRng = ("F3:F44")
Each Cell In SelecRng
Set objShell = CreateObject("Wscript.Shell")
objShell.Run (Cell)
Next
End Sub
I don't wanna see the error whenever I try to open some links
Tim Stack provides a good answer, however I would recommend running the check with = vbNullString instead of = "", and to use Cell.value2 instead of Cell.value.
In this precise example that would not really matter, but in some other cases it could; so better take the habit now.
That would be:
Private Sub CommandButton1_Click()
Dim SelecRng As Range
Set SelecRng = ("F3:F44") 'I would add a reference to the WB and WS here. Now it always refers to the active WB & WS
For Each Cell In SelecRng
If Cell.Value2 <> vbNullString Then
Set objShell = CreateObject("Wscript.Shell")
objShell.Run (Cell.Value2)
End If
Next
End Sub
Private Sub CommandButton1_Click()
Dim SelecRng As Range
Set SelecRng = ("F3:F44") 'I would add a reference to the WB and WS here. Now it always refers to the active WB & WS
For Each Cell In SelecRng
If not Cell.Value = "" Then
Set objShell = CreateObject("Wscript.Shell")
objShell.Run (Cell.Value)
End If
Next
End Sub

Trying to delete a sheet and create a new ones

I'm trying to run the program so that it deletes an already existing sheet, create a new one so that I can fill it with results. I want to be able to do this every time I run the program so that I get a new sheet without the previous results.
Dim CustomerID As Integer
Dim SameID As Integer
Dim TotalSpent As Currency
Dim HighSpenders As Integer
Dim CustomerOrder As Integer
Dim DataCell As Range
Dim ReportCell As Range
Dim UserAmount As Variant
Dim UserAmount1 As Integer
Dim wsData As Worksheet
Dim wsReport As Worksheet
Set wsData = ActiveWorkbook.Sheets("Data")
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Sheets("Report").Delete
On Error GoTo -1
Application.DisplayAlerts = True
Do
UserAmount = InputBox("Enter an amount")
If Not IsNumeric(UserAmount) Then
MsgBox "Enter a numeric value"
Else
UserAmount1 = CInt(UserAmount)
End If
Loop While Not IsNumeric(UserAmount)
Set wsReport = ActiveWorkbook.Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Report"
Set DataCell = wsData.Range("A3")
Set ReportCell = wsReport.Range("A3")
Problem now is that it's not creating a new worksheet called Report with the results
Delete Sheet ft. On Error Goto 0
If this code is in the ActiveWorkbook, you should use
ThisWorkbook instead, or refer to it by its name e.g. Workbooks(CreateReport.xlsm).
Use the With statement for objects to make the code more readable and
avoid unnecessary reference errors:
The paremeter part of the After argument After:=Sheets(Sheets.Count) ' is, I would say, incorrect and should have been:
After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count).
Why does it then still work correctly? It's because when omitting ActiveWorkbook, the ActiveWorkbook is actually used ('understood', 'default'). You could have omitted all the ActiveWorkbook references you used and all the Sheets would still have (correctly) referred to the ActiveWorkbook's sheets.
Why incorrect? You have decided to change all the ActiveWorkbook instances to Workbooks("CreateReport.xlsm"). You will probably not add the reference in the After argument, which could give you undesired results because it's referring to the ActiveWorkbook, which could be another workbook (not CreateReport.xlsm).
The last part lead us to another benefit of using the With statement, namely if you want to change the reference of the workbook, you will have to change it only in the With statement (once) e.g.:
With Workbooks("CreateReport.xlsm")
VBA
does not support On Error Goto -1, Visual
Basic
does. If you would have used
On Error Goto 0,
the code would have produced Run-time error '424': Object required and would have highlighted the line Set wsReport = ... and you would have immediately known that this was the line that had to be changed.
You can use the same variable UserAmount (as Variant) instead of
UserAmount1. To prevent Run-time error '6': Overflow when entering
a value that exceeds the Integer limit e.g. 32768, you should use
Long instead of Integer:
UserAmount = CLng(UserAmount)
' or:
Dim UserAmount1 as Long
...
UserAmount1 = Clng(UserAmount)
if you'll stick with variable UserAmount1.
You cannot Add a new worksheet and rename it in one go (in the same
line). You have to use two lines:
With ActiveWorkbook
Set wsReport = .Sheets.Add(After:=.Sheets(.Sheets.Count))
End With
wsReport.Name = "Report"
It is good practice to create titles or shortly describe various
sections of the code. I've probably added too many.
The Code
Sub AddSheet()
Dim CustomerID As Integer
Dim SameID As Integer
Dim TotalSpent As Currency
Dim HighSpenders As Integer
Dim CustomerOrder As Integer
Dim DataCell As Range
Dim ReportCell As Range
Dim UserAmount As Variant
'Dim UserAmount1 As Long
Dim wsData As Worksheet
Dim wsReport As Worksheet
' If this code is in the ActiveWorkbook, use ThisWorkbook instead.
With ThisWorkbook
' Create a reference to Data Sheet.
Set wsData = .Sheets("Data")
' Delete (old) Report Sheet.
On Error Resume Next
Application.DisplayAlerts = False
.Sheets("Report").Delete
Application.DisplayAlerts = True
On Error GoTo 0 ' VBA doesn't support On Error Goto -1
' Input UserAmount.
Do
UserAmount = InputBox("Enter an amount")
If Not IsNumeric(UserAmount) Then
MsgBox "Enter a numeric value"
Else
' You can use the same variable.
' To prevent "Run-time error '6': Overflow" when entering a
' value that exceeds the integer limit e.g. 32768, you have
' to use Long.
UserAmount = CLng(UserAmount)
'UserAmount1 = CLng(UserAmount)
End If
Loop While Not IsNumeric(UserAmount)
' Create a reference to a newly added sheet.
Set wsReport = .Sheets.Add(After:=.Sheets(.Sheets.Count))
End With
' Rename the newly added sheet.
wsReport.Name = "Report"
' Create references to cells "A3" of both worksheets.
Set DataCell = wsData.Range("A3")
Set ReportCell = wsReport.Range("A3")
End Sub
You re not declaring or Setting wsData or wsReport. This will at least set wsReport to the newly created worksheet.
Dim CustomerID As Integer, SameCustomerID As Integer
Dim TotalSpent As Currency
Dim HighSpenders As Integer, CustomerOrder As Integer, UserAmount1 As Integer
Dim DataCell As Range, ReportCell As Range
Dim UserAmount As Variant
dim wsData as worksheet, wsReport as worksheet
application.displayalerts = false 'do NOT ask for confirmation
on error resume next 'if Reports doesn't exist, keep going
ActiveWorkbook.Sheets("Report").Delete
on error goto -1 'reset the error handler
application.displayalerts = true 'turn alerts back on
Do
UserAmount = InputBox("Enter an amount")
If Not IsNumeric(UserAmount) Then
MsgBox "Enter a numeric value"
Else
UserAmount1 = CInt(UserAmount)
End If
Loop While Not IsNumeric(UserAmount)
set wsReport = ActiveWorkbook.workSheets.Add(After:=Sheets(Sheets.Count))
with wsReport
.Name = "Report"
end with
Set ReportCell = wsReport.Range("A3")
'wsData is still not set to any worksheet
Set DataCell = wsData.Range("A3")

VBA to delete multiple RangeNames for single Range

I have searched for an answer for hours, and can't search anymore. Have Seen lots of discussions about deleting all range names from a workbook or a worksheet. However, I need to delete multiple Range Names from a single Range while leaving other Range Names for other ranges on the same sheet and/or within the same workbook alone. Might the code look something like this?:
Sub Delete_My_Named_Ranges()
Dim nName As Name
Dim wbk As Workbook
Dim Sht As Worksheet
Dim rgNm As Range, aCell As Range
Set wbk = Workbooks("testRgNmDelete.xlsm")
Set Sht = wbk.Worksheets("Sheet1")
Set rgNm = Sht.Range("$A$1")
For Each nName In ThisWorkbook.Names
Set aCell = Range(nName)
If Not Intersect(aCell, rgNm) Is Nothing Then
nName.Delete
End If
Next
End Sub
OK, the above code works for a fixed range ("$A:$1"). But I need to be able to set rgNm as a variable instead of as a fixed range. here is an example, the error now is on the statement "Set aCell = Range(nName)."
Private Sub cboProductType_Change()
Dim wbSKUM As Workbook
Dim ws As Worksheet, wsLUL As Worksheet, wsLU As Worksheet
Dim rgPTL As Range, rgTable1 As Range, rgA1 As Range, rgA1LU As Range
Dim rgNm As Range, rgFormula As Range, aCell As Range
Dim sFormula As String
Dim nName As Name
Set wbSKUM = Workbooks("XBS_SKU_Master.xlsm")
Set ws = wbSKUM.Worksheets("SKUMaster")
Set wsLUL = wbSKUM.Worksheets("LookupLists")
Set wsLU = wbSKUM.Worksheets("Lookup")
Set rgPTL = wsLUL.Range("ProdTypeLookUp")
Set rgTable1 = ws.Range("Table1")
sFormula = "=SUBSTITUTE(SUBSTITUTE(F2,"" "",""_""),""-"","""")"
'clear Product Type Lookup List (Column D) to be sure no data remains
wsLUL.Activate
Range(Range("F2"), Range("F2").End(xlDown)).Select
Selection.Cells.Value = vbNullString
Set rgNm = Selection
For Each nName In ThisWorkbook.Names
Set aCell = Range(nName)
If Not Intersect(aCell, rgNm) Is Nothing Then
nName.Delete
End If
Next
Thanks again!
You are getting that error becuase you have not set rgName after declaring it.
Here is my understanding of your question.
Lets say there is a Range A1:A10 in Sheet1 and Cell A2 has a name NM1 and Cell A5 has a name NM2 and cell D10 has a name NM3
And you want a piece of code which deletes the Names in Range A1:A10 i.e NM1 and NM2 and not NM3
If the above is what you want then try this
Option Explicit
Sub Sample()
Dim rgName As Range, aCell As Range
Dim nName As Name
Set rgName = Sheets("Sheet1").Range("A1:A10")
For Each nName In ThisWorkbook.Names
Set aCell = Range(nName)
If Not Intersect(aCell, rgName) Is Nothing Then nName.Delete
Next
End Sub
And if I have misunderstood your question then you might want to rephrase it?
FOLLOWUP
This has been an extremely useful site to me as a new VBA user, but I have ABSOLUTELY no idea how to add to this site, beyond these little notes. Please try to imagine the Name Manager in Excel 2010 - in Name Manager there are say 10 unique names, all for =Sheet1!$A$1. I want all of these names which pertain to Sheet1!$A$1 to be deleted by VBA code. I DO NOT want other names to be deleted anywhere. – LostInData 3 mins ago
Based on your above comment try this
Option Explicit
Sub Sample()
Dim nName As Name
For Each nName In ThisWorkbook.Names
If nName.RefersTo = "=Sheet1!$A$1" Then nName.Delete
Next
End Sub
I think there is something missing in the solution given above.
In order to refer to the range of a named range with the range object you must use the name property of your named range. Therefore, not Set aCell = Range(nName) but rather Set aCell = Range(nName.Name).
Like this:
Option Explicit
Sub Sample()
Dim rgName As Range, aCell As Range
Dim nName As Name
Set rgName = Sheets("Sheet1").Range("A1:A10")
For Each nName In ThisWorkbook.Names
Set aCell = Range(nName.Name)
If Not Intersect(aCell, rgName) Is Nothing Then nName.Delete
Next
End Sub

Resources