Sub Auto_Open()
' Clean current connections and query tables
' https://stackoverflow.com/a/49135238/213871
Dim cn
Dim qt As QueryTable
Dim ws As Worksheet
For Each cn In ThisWorkbook.Connections
cn.Delete
Next
For Each ws In ThisWorkbook.Worksheets
For Each qt In ws.QueryTables
qt.Delete
Next
Next ws
' Clear all contents except header row
Rows("2:" & Rows.Count).ClearContents
' Add the connection to the csv file in the same folder
' Inspired from https://stackoverflow.com/a/40536980/213871
Dim csvFileName As String
csvFileName = "DatabaseView.csv"
Dim filePath As String
filePath = ActiveWorkbook.Path
Dim conString As String
conString = "TEXT;" & filePath & "\" & csvFileName
' Add the connection to DataBaseView.csv
With ActiveSheet.QueryTables.Add(Connection:= _
conString _
, Destination:=Range("$A$2"))
.Name = "DatabaseView"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 1
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
3条答案
按热度按时间kpbwa7wx1#
根据进一步的研究,不使用工作簿路径编写VBA/宏脚本是不可能的。
jaql4c8m2#
通过VBA,可以在创建数据导入时记录宏,然后检查生成的VBA。您可以修改宏并将其用于从任何位置加载数据。
0ve6wy6x3#
创建启用宏的excel工作簿(.xlsm),将其保存在某个位置并添加以下宏:
调整csv文件、范围(当前为“$A$2”)和分隔符选项(您可以在从UI添加导入以获取模板时录制宏)。
Auto_Open()
宏将导致它在文件启动时加载。使用Excel 2010测试。