[英]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.