Excel文件对话框出现多次

我正在使用Application.FileDialog(msoFileDialogOpen)来允许用户select一个文件来从中导入数据。 但是,在用户select一个文件后,它会popup打开文件对话框,要求他们select一个文件。 它会做2-3次,然后继续。

我不小心创build了一个循环?

 Private Sub CommandButton1_Click() Set myFile = Application.FileDialog(msoFileDialogOpen) With myFile .Title = "Choose File" .AllowMultiSelect = False If .Show <> -1 Then Exit Sub ElseIf .Show <> 0 Then FileSelected = .SelectedItems(1) End If End With 'data location & range to copy mydata = "='[FileSelected]'!$C$10:$C$21" '<< change as required 'link to worksheet With ThisWorkbook.Worksheets(1).Range("C10:C21") '<< change as required .Formula = mydata 'convert formula to text .Value = .Value End With End Sub 

所以我已经尝试了你的每个解决scheme,而且我仍然得到两个打开的文件对话框,但是之前我没有注意到两者之间的区别。 第一个盒子有适当的“select文件”标题,但是第二个盒子具有标题的“更新值:文件select”。 我还添加了之前排除的最后几行。 再次感谢你的帮助。

.Show方法类似于Userform.Show显示文件对话框。 所以每次打电话时都会显示对话框。

 With Application.FileDialog(msoFileDialogOpen) .Title = "Choose File" .AllowMultiSelect = False .Show If .SelectedItems.Count = 0 Then Exit Sub Else FileSelected = .SelectedItems(1) End If End With 

你可以缩短它:

 filepath = Application.GetOpenFilename("All files (*.*),*.*") If filepath = False Then Exit Sub MsgBox filepath 

在你的代码中,你要调用Show方法两次。 因此对话框显示两次。 尝试以下代替…

 Private Sub CommandButton1_Click() Dim strPathAndFile As String With Application.FileDialog(msoFileDialogOpen) .Title = "Choose File" .AllowMultiSelect = False If .Show <> -1 Then Exit Sub strPathAndFile = .SelectedItems(1) End With End Sub 

希望这可以帮助!