将变量路径CSV直接导入表中



我正在尝试将CSV文件"用户角色权限"中的数据导入到我的当前工作表(当前工作表选项卡名称也是"用户角色权利"(,如果将其导入单元格A1,则该工作表运行良好。但是,如果我尝试使用一个表,代码将不起作用。我知道这是一个小调整,然而,我无法弄清楚。

注意:我的文件在同一文件夹中,并且我正在使用可变路径导入VBA代码。

我的代码如下:

Dim path As String
path = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(ThisWorkbook.path)
Sheets("User Roles Entitlements").Select
Range("A1").Select
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & path & "User Roles Entitlements.csv", Destination:=Range("A1"))
.Name = "positions_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 857
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub

如果我能得到帮助,我将不胜感激。

如果导入后数据连接丢失,您可以吗?换句话说,在引入CSV文件后,是否需要动态刷新该表?

如果答案是否定的,那么您可以简单地将该范围转换为事实之后的ListObject(表(。

为了方便起见(这样以后就不必计算出范围了(,您可以在对QueryTable对象进行抓取之前从中捕获该范围

Sub CsvInsert()
Dim sh As Worksheet
Dim qt As QueryTable
Dim r As Range
Set sh = Sheets("User Roles Entitlements")
Set qt = sh.QueryTables.Add(Connection:="TEXT;" & path & _
"User Roles Entitlements.csv", Destination:=Range("A1"))
With qt
.Name = "positions_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 857
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With

然后将查询表转换为一个范围,并在该范围上创建一个表:

Set r = qt.ResultRange
sh.QueryTables("positions_1").Delete
sh.ListObjects.Add(xlSrcRange, r).Name = "positions_1"
End Sub

最新更新