VBA Excelselect文件 – 单击取消时清除文本框

基本上我有一个电子表格,它的forms。 在那个表单上有一个文本框,其中包含一个文件path,可以从工作表上的单元格预先填充。 但用户可以select浏览另一个文件。 当他们浏览时,他们可以select“打开”或“取消”。 打开button工作正常,填充文本框,但如果他们select取消它清除文本框,如果它已经填充。 我怎样才能停止被清除的文本框?

我已经把它缩小到这个代码块的地方了:

Function GetFileName() Set MyFile = Application.FileDialog(msoFileDialogOpen) With MyFile .Title = "Choose File" .AllowMultiSelect = False If .Show <> -1 Then Exit Function End If GetFileName = .SelectedItems(1) End With End Function 

这做了伎俩。 在填充文本框之前确保文件名有一个值

 Private Sub btnBrowse_Click() Dim sFileName As String sFileName = GetFileName() If Len(sFileName) > 0 Then TextBox1.Value = sFileName End If End Sub Function GetFileName() Set MyFile = Application.FileDialog(msoFileDialogOpen) With MyFile .Title = "Choose File" .AllowMultiSelect = False If .Show <> -1 Then Exit Function End If GetFileName = .SelectedItems(1) End With End Function