[英]Importing data from csv to excel
我有一個重復的過程,其中包括將數據從不同的 csv 文件導入到 excel
當前過程從數據手動導入數據>從文本>選擇所需文件>選擇分隔且我的數據有標題>選擇分隔符逗號>下一步>完成>新工作表
有沒有辦法制作一個 vba 腳本/宏,它會提示用戶他們想要導入什么文件並選擇我選擇的選項
感謝致敬
這是我前段時間使用的一些代碼。
Dirlocal
是.csv
文件的路徑
我會將數據導入名為“ODK”的工作表中
Dim ws As Worksheet
Dim strText As String
' read utf-8 file to strText variable
With CreateObject("ADODB.Stream")
.Open
.Type = 1 ' Private Const adTypeBinary = 1
.LoadFromFile DirLocal
.Type = 2 ' Private Const adTypeText = 2
.Charset = "utf-8"
strText = .ReadText(-1) ' Private Const adReadAll = -1
End With
' parse strText data to a sheet
Set ws = Worksheets("ODK")
intRow = 1
Application.DisplayAlerts = False
For Each strLine In Split(strText, Chr(10))
If strLine <> "" Then
With ws
.Cells(intRow, 1) = strLine
.Cells(intRow, 1).TextToColumns Destination:=Cells(intRow, 1), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False
End With
intRow = intRow + 1
End If
Next strLine
Application.DisplayAlerts = True
ReadUTF8CSVToSheet = ws.Name
您可以使用 Application.getopenfilename 選擇要打開的所需文件。 正如其中一條評論中提到的,使用宏記錄器獲取操作數據的代碼是一個好的開始,您可以將其添加到此代碼中。
Sub Button1_Click()
Dim s, wb As Workbook
s = Application.GetOpenFilename("CSV Files (*.csv),*.csv", , "Please select CSV file...")
If s <> False Then
Set wb = Workbooks.Open(s)
MsgBox "Code to Do something here"
wb.Close False
Else: MsgBox "Nothing Selected"
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.