Sub ImportTextFile()
Dim rPaht As String
Dim rFileName As String
rPaht = Sheet1.Range("C9")
rFileName = Sheet1.Range("C10")
Range("G8").CurrentRegion.Offset(1, 0).Clear
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & rPaht & "\" & rFileName & ".txt", Destination:= _
Range("$g$9"))
.Name = Sheet1.Range("C10").Value
.TextFilePlatform = 874
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileOtherDelimiter = ":"
.Refresh BackgroundQuery:=False
End With
Sheet1.Range("C9") = rPaht
Sheet1.Range("C10") = rFileName
End Sub
这是我使用的代码。我遇到的问题是,每当我将一些文本文件导入到表中时,它就会清除表格中的所有内容,包括表格行和格式
我想问是否有任何方法将文本文件导入我们想要的区域而不伤害其他单元格
答案 0 :(得分:0)
我会使用文件脚本对象来读取文本文件。此示例使用后期绑定,但您也可以提前绑定它。读取变量然后将该变量设置为输出范围会更有效。
Sub ImportTextFile()
Dim rPath As String, rFileName As String, fs As Object, fsFile As Object, iLine As Integer
rPath = Sheet1.Range("C9")
rFileName = Sheet1.Range("C10")
Range("G8").CurrentRegion.Offset(1, 0).Clear
'Use filescripting object to open the file on Windows
Set fs = CreateObject("Scripting.FileSystemObject")
Set fsFile = fs.OpenTextFile(rPath & "\" & rFileName, 1, False)
'Loop through the file
Do While fsFile.AtEndOfStream <> True
iLine = iLine + 1
Sheet1.Cells(iLine + 8, 1) = VBA.Split(fsFile.ReadLine, vbTab)
Loop
Set fs = Nothing
Set fsFile = Nothing
End Sub