Match fails and kills macro

Glory

Well-known Member
Joined
Mar 16, 2011
Messages
640
a = Application.WorksheetFunction.Match("a", Range("J1:J10"))
MsgBox a

I was just going to do if isempty(a) later on, but it turns out it doesn't just leave the variable empty if there's no match... it errors out.

Is there a simple way to get around this problem without an error handler?

Error: "Unable to get the match property of the worksheet function class"
 

Excel Facts

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.
Glory,


You are missing one part of the Match Function:

match_type Optional. The number -1, 0, or 1. The match_type argument specifies how Excel matches


This:
a = Application.Match("a", Range("J1:J10"))

Should be:

a = Application.Match("a", Range("J1:J10"), 0)




Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).


Code:
Option Explicit
Sub Test()

Dim a As Long

a = 0
On Error Resume Next
a = Application.Match("a", Range("J1:J10"), 0)
On Error GoTo 0
If a = 0 Then
  MsgBox "'a' was not found in range J1:J10"
Else
  MsgBox a
End If

End Sub
 
Upvote 0

Forum statistics

Threads
1,214,591
Messages
6,120,425
Members
448,961
Latest member
nzskater

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top