0
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

这是我使用的代码。我遇到的问题是,每次我将一些文本文件导入表格时,它都会清除表格上的所有内容,包括表格行和格式

我想问一下是否有将文本文件导入我们想要的区域而不损害其他单元格

4

1 回答 1

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
于 2012-12-07T04:49:33.017 回答