我有7个csv文件和一个xls文件。在xls文件中我有7张(每个csv文件一张)。我可以创建一个数据连接,将每个csv文件读取到给定的表单中。但是,当我压缩xls和7个csv文件并将它们发送给他们无法打开的人时,请查看xls文件中的数据,因为它试图访问我计算机上的文件(C:/ Desktop / MyComputerName / FILE.CSV)。是否有可能使这个链接相对?有没有不同的方法来访问csv文件的内容而不是逐个单元地进行?
答案 0 :(得分:9)
根据进一步的研究,如果不使用工作簿路径编写VBA /宏脚本,则无法实现。
答案 1 :(得分:1)
可以通过VBA,在创建数据导入时记录宏,然后检查生成的VBA。您可以修改宏并使用它从任何位置加载数据。
答案 2 :(得分:0)
创建一个启用宏的excel工作簿(.xlsm),将其保存在某个位置并添加以下宏:
replace(max.col(-DT[, -1] == 0, ties.method = 'first') + 1, rowSums(DT == 0) == 0, NA)
#or break it into two lines If you want,
i1 <- max.col(-DT[,-1] == 0, ties.method = 'first') + 1
replace(i1, rowSums(DT == 0) == 0, NA)
#[1] 2 3 2 4 NA
调整csv文件,范围(当前为“ $ A $ 2”)和定界符选项(您可以在从UI添加导入以获得模板时记录宏)。 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
宏将导致它在文件启动时加载。经过Excel 2010的测试。