Excel VBA 忽略我的 IF 语句退出子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21877106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA ignores my IF statement to exit the sub
提问by rohrl77
Excel ignores my programming statement that it should exit the sub if the item count is nothing
Excel 忽略我的编程语句,即如果项目计数为零,它应该退出子程序
Given that it ignored the first IF statement, I tried to simply catch it with a second one, but it ignores that as well!
鉴于它忽略了第一个 IF 语句,我试图简单地用第二个语句捕获它,但它也忽略了它!
The code not only executes, but it just skips over all statements, and if I try to go through it line by line using F8, then it executes the full code.
代码不仅会执行,而且会跳过所有语句,如果我尝试使用 F8 逐行浏览它,则会执行完整代码。
I don't understand why it does this or what could cause it... Any help is appreciated.
我不明白为什么它会这样做或可能导致它......任何帮助表示赞赏。
Private Sub SelectFolder()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & " \"
.Title = "Select Folder"
.Show
If .SelectedItems.Count = 0 Then
Exit Sub
Else
sPfad = .SelectedItems(1)
End If
End With
If sPfad = "" Then Exit Sub
End Sub
UPDATE: After getting this response which worked well when I tried it stepping through the code automatically, I realized that when I ran the whole procedure, my problem persisted.
更新:当我尝试自动单步执行代码时,得到这个运行良好的响应后,我意识到当我运行整个过程时,我的问题仍然存在。
Today I finally learned what is happening... the sub does in fact, as programmed, stop and end. THAT particular sub. However, since I'm calling it from a different sub in a procedure, the code then goes back to the calling sub and continues.
今天我终于知道发生了什么……潜艇确实按照程序停止并结束。那个特别的子。但是,由于我是从过程中的不同子程序调用它,因此代码会返回到调用子程序并继续。
What I needed was simply to change Exit Sub
to End
since I needed the whole procedure to stop!
我需要的只是改变Exit Sub
,End
因为我需要停止整个过程!
回答by Dmitry Pavliv
Try this one:
试试这个:
Sub SelectFolder()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & " \"
.Title = "Select Folder"
If Not .Show Then Exit Sub
sPfad = .SelectedItems(1)
End With
End Sub
when user press "Cancel"- .Show
returns 0
(False
). But if user press "OK"- current folder in FileDialog windowis selected
当用户按下“取消”时-.Show
返回0
( False
)。但是如果用户按“确定”- FileDialog 窗口中的当前文件夹被选中
回答by Pedrumj
A different approach:
一种不同的方法:
Private Sub SelectFolder()
Dim strPath As Variant
Dim sPfad As Variant
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & " \"
.Title = "Select Folder"
End With
strPath = Application.FileDialog(msoFileDialogFolderPicker).Show
If strPath = False Then
Exit Sub
Else
sPfad = strPath
End If
End Sub