VBA User Selected Range Error on Cancel

jscranton

Well-known Member
Joined
May 30, 2011
Messages
707
I have been using this bit of code to get a user selected column (uses worksheet and string inputs). HOwever, if the user selects cancel, it errors out. Interestingly, it was working until I declared all my variable types. Any idea how to work around the error?

Thanks,

Justin

Code:
Private Function getCol(sh As Worksheet, s As String) As Integer
Dim x
Dim y
Dim checkS As String
Dim a() As Variant
Dim rng As rng


sh.Activate
Set rng = Application.InputBox("Select the COLUMN containing the " & s, s, , , , , , 8)


getCol = rng.Column


End Function
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
I presume that in your declarations you meant ..
Rich (BB code):
Dim rng As Range
.. though that will not solve the Cancel problem.
(You have also declared some variables that are not used in the function)

You could try this. The function will then return 0 if Cancel is clicked

Rich (BB code):
sh.Activate
On Error Resume Next
Set rng = Application.InputBox("Select the COLUMN containing the " & s, s, , , , , , 8)
On Error GoTo 0
If Not rng Is Nothing Then
  getCol = rng.Column
End If
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,429
Messages
6,119,433
Members
448,897
Latest member
ksjohnson1970

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