Excel宏 - 如果未选择文件,则运行打开文件对话框

时间:2014-02-17 03:21:49

标签: excel excel-vba dialog vba

我有一个宏(下方),打开对话框选择文件并将其打开到“投资”表格,然后运行宏来将投资文件分解为选定的数据

但是,如果某人按下取消或关闭对话框,则用于细分投资表的宏仍会运行。

有人可以帮我阻止这个错误,那么如果没有选择文件,故障宏就不会运行了吗?

Sub Import()
  ' Imports file '
  Application.ScreenUpdating = False
  Dim WS As Worksheet, strFile As String
  Set WS = ActiveWorkbook.Sheets("Invest")
  strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please selec text file...")
  With WS.QueryTables.Add(Connection:="TEXT;" & strFile, _
      Destination:=WS.Range("A1"))
      .FieldNames = True
      .RowNumbers = False
      .FillAdjacentFormulas = False
      .PreserveFormatting = True
      .RefreshOnFileOpen = False
      .RefreshStyle = xlInsertDeleteCells
      .SavePassword = False
      .SaveData = True
      .AdjustColumnWidth = True
      .RefreshPeriod = 0
      .TextFilePromptOnRefresh = False
      .TextFilePlatform = 850
      .TextFileStartRow = 1
      .TextFileParseType = xlDelimited
      .TextFileTextQualifier = xlTextQualifierDoubleQuote
      .TextFileConsecutiveDelimiter = False
      .TextFileTabDelimiter = True
      .TextFileSemicolonDelimiter = False
      .TextFileCommaDelimiter = True
      .TextFileSpaceDelimiter = False
      .TextFileTrailingMinusNumbers = True
      .Refresh BackgroundQuery:=False
  End With
  ' Imports file '
  '''''''
  'RUN MACRO CODE HERE
  '''''''
End Sub

1 个答案:

答案 0 :(得分:2)

我认为处理你所寻找的错误是这样的:

Dim fn As String
fn = Application.GetOpenFilename("All Files,.", 1, "Select a file", , False)

If fn = "False" Then
    Exit Sub
End If

这来自另一个Stackoverflow页面 Excel VBA Open File (error handling)