我正在尝试将数据从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
如果能在此方面获得帮助,将不胜感激。
答案 0 :(得分:1)
如果导入后数据连接丢失,可以吗?换句话说,导入表格后,是否需要从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