[英]Cancel reading a file VBA
我有這段代碼可以讓用戶從他的電腦中選擇一個文件,然后在 excel 中解析它,它工作正常但是如果我點擊取消(我選擇沒有文件)它會返回一個錯誤,創建一個空白表,我該怎么做這樣做只會取消整個過程。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.