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
Related
My code returns with an error. The result is as wished, but the error message is rather annoying. How can I get rid of this?
Sub SELECTIE_VERZUIM()
Dim Cval As Variant
Dim Rng1 As Range
Cval = Sheet4.Range("A16").Value
Set Rng1 = Sheet4.Range("D1:T" & Cval).Select
End Sub
Run-time error '424':
Object required
Try:
Sub SELECTIE_VERZUIM()
Dim Cval As Variant
Cval = Sheet4.Range("A16").Value
Sheet4.Range("D1:T" & Cval).Select
End Sub
Also, you should avoid using Select in VBA
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")
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")
I've been searching how to assign a row to a variable and manipulate cells through the variable but I can't seem to find how to do this.
x = Sheet5.Range("A1").EntireRow
MsgBox x(1, 1)
The above code will get me the row into 'x', but is there any way that I can change a cells value using the variable 'x'? x(1,1) = "foo" will not work, and since it's not an object I can't access .Value.
Here's some sample code:
Sub Ranging()
Dim rng As Excel.Range
Dim ws As Excel.Worksheet
Set ws = ActiveSheet
Set rng = ws.Range("A1").EntireRow
With rng
Debug.Print .Cells(1).Value
Debug.Print .Cells(5).Address
.Cells(43).Value = "SurfN'Turf"
End With
End Sub
Debug.Print prints to the VBE's Immediate Window (access with Ctrl-G)
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