首页 文章

vba:将文本文件导入Excel工作表

提问于
浏览
15

我正在编写一个vba代码,该代码应该删除所选Excel工作表上的数据,打开一个文本文件选择对话框,然后将该文本文件中的数据导入到我删除数据的同一个工作表中 . 到目前为止,我只能将文本文件打开到新工作簿中,但无法将其打开到我从中删除数据的同一工作表 . 这是我到目前为止所提供的内容,非常感谢您的帮助:

Dim Filt As String
Dim FilterIndex As Integer
Dim Title As String
Dim FileName As Variant

Filt = "Cst Files (*.prn),*.prn"
Title = "Select a cst File to Import"
FileName = Application.GetOpenFilename(FileFilter:=Filt, Title:=Title)

If FileName = False Then
MsgBox "No File Was Selected"
Exit Sub
End If

With Application.ActiveSheet
    Cells.Select
Selection.QueryTable.Delete
Selection.ClearContents
End With

Workbooks.Open FileName

谢谢!

3 回答

  • 0

    您可以通过多种方法将文本文件导入当前工作表 . 这里有三个(包括你上面使用的方法)

    • 使用QueryTable

    • 在内存中打开文本文件,然后写入当前工作表,最后根据需要应用“文本到列” .

    • 如果要在新工作簿中打开文本文件后使用当前使用的方法,只需使用 Cells.Copy 将其复制到当前工作表中 .

    Using a QueryTable

    这是我记录的一个简单的宏 . 请根据您的需要进行修改 .

    Sub Sample()
        With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
            )
            .Name = "Sample"
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
    End Sub
    

    Open the text file in memory

    Sub Sample()
        Dim MyData As String, strData() As String
    
        Open "C:\Sample.txt" For Binary As #1
        MyData = Space$(LOF(1))
        Get #1, , MyData
        Close #1
        strData() = Split(MyData, vbCrLf)
    End Sub
    

    获得数组中的数据后,可以将其导出到当前工作表 .

    Using the method that you are already using

    Sub Sample()
        Dim wbI As Workbook, wbO As Workbook
        Dim wsI As Worksheet
    
        Set wbI = ThisWorkbook
        Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
    
        Set wbO = Workbooks.Open("C:\Sample.txt")
    
        wbO.Sheets(1).Cells.Copy wsI.Cells
    
        wbO.Close SaveChanges:=False
    End Sub
    

    FOLLOWUP

    您可以使用 Application.GetOpenFilename 选择相关文件 . 例如...

    Sub Sample()
        Dim Ret
    
        Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
    
        If Ret <> False Then
            With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;" & Ret, Destination:=Range("$A$1"))
    
                '~~> Rest of the code
    
            End With
        End If
    End Sub
    
  • 36

    你可以写.WorkbookConnection.Delete .Refresh BackgroundQuery:= False这将删除文本文件外部连接 .

  • 1

    我认为my answer to my own question这是您尝试做的最简单的解决方案:

    • 选择文件中第一行文本所在的单元格 .

    • 使用 Data / Get External Data / From File 对话框选择要导入的文本文件 .

    • 根据需要格式化导入的文本 .

    • 在打开的 Import Data 对话框中,单击 Properties...

    • 取消选中 Prompt for file name on refresh 框 .

    • 每当外部文件发生变化时,单击 Data / Get External Data / Refresh All 按钮 .

    注意:在您的情况下,您可能希望跳过步骤#5 .

相关问题