簡體   English   中英

Excel VBA宏讀取文本文件,在單獨的單元格中一行

[英]excel vba macro reading text files, one line in separate cell

文本文件如下所示

a,約翰,“ 2014-2”,...

d,威爾,“ 2016-7”,...

我想將元素a放入第1行col 1中 ,將John放入第1行col 2中 ,將d放入單元格第2行col 1中 ,等等。請幫忙。 謝謝。 下面是我的代碼

Sub Importdata()
Open "C:\Users\apple\desktop\12345.txt" For Input As #1
r = 0
  Do Until EOF(1)
    Line Input #1, Data
    ActiveCell.Offset(r, 0) = Data
    r = r + 1
  Loop
Close #1
End Sub

您可以使用分割每行Split,作為分隔符

試試這個可以正常工作:

Option Explicit

Sub Importdata()

Dim cet
Dim r As Long
Dim Data
Dim wk AS worksheet

Set wk = sheet1

Open "C:\Users\apple\desktop\12345.txt" For Input As #1
r = 1

  Do Until EOF(1)
    Line Input #1, Data
    cet = Split(Data, ",")

    if len(join(cet)) > 0 then        
     wk.Cells(r, 1) = cet(0)
     wk.Cells(r, 2) = cet(1)
    ENd if

     r = r + 1
  Loop
Close #1
End Sub

您可以使用QueryTables屬性,一步就可以導入和解析行。 最簡單的方法是使用“宏記錄器”(使用Excel菜單中的“ Data ► Get External Data ► From Text選項),然后進行調整以適應需要。 在Excel中,這將彈出“文本導入”向導,但是您也可以在VBA中進行操作。 下面是我瀏覽文件的示例,但是您可以像在原始宏中一樣輕松地對其進行硬編碼。 還要注意,我已經明確聲明了工作簿和工作表。 您可以根據需要輕松更改此設置。

EDIT添加了一些細微調整以進行澄清

Option Explicit
Sub ImportData()
    Dim sMyFile As Variant
    Dim WS As Worksheet, WB As Workbook

Set WB = ThisWorkbook
Set WS = WB.Worksheets("sheet1")

sMyFile = Application.GetOpenFilename("Text Files(*.txt), *.txt")
If sMyFile <> False Then

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

End If

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM