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
 

Some videos you may like

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).

Peter_SSs

MrExcel MVP, Moderator
Joined
May 28, 2005
Messages
47,926
Office Version
  1. 365
Platform
  1. Windows
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:

Watch MrExcel Video

Forum statistics

Threads
1,122,737
Messages
5,597,826
Members
414,180
Latest member
Sir Khaya

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
Top