Excel/VBA Code

Advertisement


Question
I use the following code to match values from a table. When I make a typo that is not represented in the table I get a debug message. Is there a way to just get a message box instead of having to debug each time?

Sub INdex_Match1()
  Dim wksWatch As Worksheet, wksDash As Worksheet
  Dim colA As Range, colB As Range
  Set wksDash = ThisWorkbook.Sheets("DashBoard")
  Set wksWatch = ThisWorkbook.Sheets("(5) Watch List")
  Set colA = wksWatch.Range("A3:A1000")
  Set colB = wksWatch.Range("B3:B1000")
  wksDash.Range("M7") = _
      colB.Cells(Application.Match(wksDash.Range("D7"), _
      colA, 0), 1)
   wksDash.Range("N7") = _
      colB.Cells(Application.Match(wksDash.Range("D7"), _
      colA, 0), 3)
   wksDash.Range("O7") = _
      colB.Cells(Application.Match(wksDash.Range("D7"), _
      colA, 0), 4)
End Sub

Answer
Hi dp,

try this out

Sub INdex_Match1()
   Dim wksWatch As Worksheet, wksDash As Worksheet
   Dim colA As Range, aCell As Range
   Set wksDash = ThisWorkbook.Sheets("DashBoard")
   Set wksWatch = ThisWorkbook.Sheets("(5) Watch List")
   Set colA = wksWatch.Range("A3:A1000")

   Set aCell = colA.Find(What:=wksDash.Range("D7").Value, LookIn:=xlValues, _
                         LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                         MatchCase:=False, SearchFormat:=False)

   If aCell Is Nothing Then

       MsgBox "Item not found"

   Else
       wksDash.Range("M7") = aCell.Offset(0, 1)
       wksDash.Range("N7") = aCell.Offset(0, 2)
       wksDash.Range("O7") = aCell.Offset(0, 3)

   End If

End Sub

About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here

Excel

All Answers


Answers by Expert:


Ask Experts

Volunteer


Dave Morrison

Expertise

I can answer most excel questions My Website is davesexcel.com

Experience

I have been working with spreadsheets since 1991. I am a self-trained excel developer since 2005.

Publications
My website davesexcel.com

Education/Credentials
Business admin. U of R.

Awards and Honors
Microsoft Excel MVP 2011-2012

©2016 About.com. All rights reserved.