取消读取VBA文件



我有这样的代码,可以让用户从他的电脑中选择一个文件,然后在excel中解析它。它运行良好,但如果我单击取消(我不选择任何文件(,它会返回一个创建emty表的错误,我该如何做,它只会取消整个过程。

Public Sub Lecturee()
Dim ws As Worksheet, strFile As String
Set ws = ActiveWorkbook.Sheets.Add
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please selec text file...")
With ws.QueryTables.Add(Connection:="TEXT;" & strFile, _
Destination:=ws.Range("A1"))
.TextFilePlatform = 65001
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
ws.name = "Lecture"
MsgBox "fichier ouvert"
End Sub
Option Explicit
Public Sub Lecturee()
Dim ws As Worksheet, strFile As Variant
strFile = Application.GetOpenFilename("CSV Files (*.csv),*.csv", , "Please selec text file...")
If strFile <> False Then
MsgBox "fichier ouvert" & strFile
Set ws = ActiveWorkbook.Sheets.Add
With ws.QueryTables.Add(Connection:="TEXT;" & strFile, _
Destination:=ws.Range("A1"))
.TextFilePlatform = 65001
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
ws.name = "Lecture"
Else: strFile = False
End If
End Sub

最新更新