【问题标题】:Want to import bits (a couple of rows) of an .txt to excel想要将 .txt 的位(几行)导入到 Excel
【发布时间】:2017-07-05 14:35:16
【问题描述】:

嘿,所以我找到了一个特定的查询,可以将文件从特定行导入 excel,并在每次再次打开时删除以下数据。但是是否也可以停止在特定行添加行?例如,如果该行中有一个特定的单词,是否可以省略一些行?

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\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, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
        
    End With
End Sub

【问题讨论】:

    标签: vba excel import


    【解决方案1】:

    您可以这样做,但不能使用 Querytable。 试试这个代码:

    Private Sub Open_Click()
    Dim fn As Variant, myLine As Long, txt As String, x As Variant, ouput As String
    Dim i As Integer, j As Integer: j = 1
    Dim sht As Worksheet
    
    Set sht = Worksheets("Sheet1") 'Modify Sheet Name
    
    fn = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
           "Open File")
    If fn = False Then Exit Sub
    txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
    x = Split(txt, vbNewLine)
    
    For i = 0 To UBound(x)
        If x(i) <> "SomeCriteria" Then 'Check for some criteria
            sht.Cells(j, 1).Value = x(i)
            j = j + 1
        End If
    Next i
    End Sub
    

    所以它的基本作用是打开一个用户选择的 txt 文件并将其存储在变量 txt 中。将可以使用split-函数的行分开。现在每一行都存储在数组x 中。您可以通过阵列/每一行并取出您想要的那些。要检查特定单词是否在一行中,请使用InStr-函数。

    【讨论】:

    • 谢谢你的回答,你能告诉我我在哪里插入文本文件,我需要在哪里更改代码并输入我的文本文件的线程?
    • 运行代码,它会打开一个文件对话框,你可以选择一个.txt文件。
    • 好的,是的,它打开了对话框,但之后它在一个消息框中显示了结果,但没有将它导入到工作表中,我需要改变什么吗?
    • 这只是一个示例,而不是针对您的确切问题的解决方案。这些行存储在数组x 中,使用它可以将您想要的行放入工作表中。
    • 您能解释一下如何使用数组 x 来确定特定的行吗?
    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多