简体   繁体   中英

Cancel reading a file VBA

I have this code that'll let the user choose a file from his pc and then parse it in excel, It works fine but in case I click cancel (i choose no file ) it returns an error creating an emty sheet, How do i do so it'll just cancel the whole process.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM