【问题标题】:How to exit sub on InputBox if cancel is selected but continue with code if ok is selected如果选择取消,如何在 InputBox 上退出子程序,但如果选择确定,则继续执行代码
【发布时间】:2018-07-27 03:59:37
【问题描述】:
    Sub Export_Click()

Dim Rng As Range
Dim WorkRng As Range
Dim vFile As Variant
Dim x As Range
On Error Resume Next

    TitleId = "Export to CSV file"
    x = WorkRng

Set WorkRng = Range("D12:I100")
Set WorkRng = Application.InputBox("Range", TitleId, WorkRng.Address, Type:=8)

    If x = "" Then Exit Sub

    Application.ActiveSheet.Copy
    Application.ActiveSheet.Cells.Clear
    WorkRng.Copy Application.ActiveSheet.Range("A1")

    vFile = Application.GetSaveAsFilename(InitialFileName:=".csv", _
        FileFilter:="CSV files (*.csv), *.csv, All files (*.*), *.*")

If vFile <> False Then ThisWorkbook.SaveAs Filename:=vFile, FileFormat:=xlCS

End Sub

我有一个宏,可以将一组范围导出到 CSV 文件。如果在 InputBox 上选择了取消,我希望宏退出 Sub,但如果选择了 OK,则执行代码。

无论选择 OK 还是 Cancel,我上面的代码都会退出 sub。 如果没有 If x = "" Then Exit Sub 语句,无论选择 ok 还是 Cancel,代码都会导出到 csv。我在下面尝试了其他一些选项,看起来问题可能在于输入是一个范围。我相对缺乏经验,并且在搜索此站点和其他站点时已经没有想法了。

我已经参考链接尝试了代码的变体:

Handle cancellation of InputBox to select range

我也尝试过合并以下代码,但是无论选择“确定”还是“取消”,它都会导致退出子:

sub inputbox_verification()

 text=inputbox("type the text")

 if StrPtr(text)=0 then
 'if it entenrs here then the user pressed "cancel"
 endif

 if text=""
 'if enters here the user left in blank
 end if

 if text<>""
 'if enters here the user entered some text
 end if

 end sub 

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果选择了Cancel,则输入框返回False,因此需要以下代码:

    Dim Text As Variant 'You can ommit "As Variant"
    Text = Inputbox("Type the text")
    'Check for Text type
    If TypeName(Text) = "Boolean" Then
        'Check if it is False
        If Not Text Then Exit Sub
    End If
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2019-08-14
    • 2012-07-03
    相关资源
    最近更新 更多