Capture InputBox vbCancel

R

Rob

Hello, I have the below code that prompts for the qty of rows to be inserted
but when the Cancel button is selected instead of providing a number and
clicking OK I get an error. I was hoping that putting the IF statement in
there would fix it but it did not. How can I fix this?

Thanks in Advance.


Sub AutoInsertRows()

'Shortcut Keystroke CTRL+Shift+A

Dim r As Integer

r = InputBox("How Many Rows?", "Auto-Insert Rows", 1)
i = 0

Do While i < r

If Not r = vbCancel Then

Selection.Insert Shift:=xlDown

i = i + 1

Else

Exit Sub

End If

Loop

End Sub
 
C

Charlie

Dim i As Long
Dim n As Long

On Error GoTo CancelInput
n = InputBox("No. of Rows")
CancelInput:

For i = 1 To n
Selection.Insert Shift:=xlDown
Next i

P.S. Throw out "Dim ... As Integer" Get in the habit of always using Long.
You won't regret it.
 
G

Gary Keramidas

i usually use application.inputbox. cancel will return 0

lookup InputBox Method in vb help.
 
V

Vergel Adriano

Hi Rob,

I believe InputBox will return a null string if user clicks on Cancel. Try
something like this:

Sub AutoInsertRows()

'Shortcut Keystroke CTRL+Shift+A

Dim r As String

r = InputBox("How Many Rows?", "Auto-Insert Rows", 1)
If r = "" Then
MsgBox "user cancelled"
Exit Sub
End If
If Not IsNumeric(r) Then
MsgBox "value must be numeric"
Exit Sub
End If
i = 0

Do While i < r

If Not r = vbCancel Then

Selection.Insert Shift:=xlDown

i = i + 1

Else

Exit Sub

End If

Loop

End Sub
 
R

Rob

Thanks A ton, it's working now.

Cheers.

Vergel Adriano said:
Hi Rob,

I believe InputBox will return a null string if user clicks on Cancel. Try
something like this:

Sub AutoInsertRows()

'Shortcut Keystroke CTRL+Shift+A

Dim r As String

r = InputBox("How Many Rows?", "Auto-Insert Rows", 1)
If r = "" Then
MsgBox "user cancelled"
Exit Sub
End If
If Not IsNumeric(r) Then
MsgBox "value must be numeric"
Exit Sub
End If
i = 0

Do While i < r

If Not r = vbCancel Then

Selection.Insert Shift:=xlDown

i = i + 1

Else

Exit Sub

End If

Loop

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top