0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[VBA]テキストファイルを取り込む

Posted at

ばい。
備忘録っす。
textファイルを取り込むコードです。

コメント無し不親切コード炸裂してます。

・・・これVBAでやる必要あるんですかね。


Sub oneLine_txt()

    Dim myFile As String
On Error GoTo err
    myFile = Application.GetOpenFilename(" TXTファイル(*.txt),*.txt, CSVファイル(*.csv),*.csv,Excelブック,*.xls*,")
    
    Dim buf As String, n As Long
    Dim allLine As Variant
    
    Open myFile For Input As #1
        Line Input #1, buf
            allLine = Split(buf, ",")
            Do Until EOF(1)
                
            Loop
            Debug.Print UBound(allLine, 2)
    Close #1
    
Exit Sub
err:
    MsgBox "インポートに失敗しました", vbCritical
End Sub

Sub AllLine_txt()

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets(1)
On eroor GoTo err
    Dim strPath As String
    strPath = Application.GetOpenFilename(" TXTファイル(*.txt),*.txt, CSVファイル(*.csv),*.csv,Excelブック,*.xls*,")
     
    Dim i As Long, j As Long
    Dim strLine As String
    Dim arrLine As Variant
    
    Dim V1 As Variant
    Dim RR As Range
    
    Dim maxRow As Long, maxCol As Long
    maxRow = count_txt_Row(strPath)
    maxCol = count_txt_Col(strPath)

    ReDim V1(1 To maxRow, 1 To maxCol)
    Set RR = Range(Cells(1, 1), Cells(maxRow, maxCol))

Open strPath For Input As #1 'csvファイルをオープン
    Dim T As Single
    T = Timer
    i = 1
    Do Until EOF(1)
       
        Line Input #1, strLine
        arrLine = Split(strLine, ",")
        
        For j = 1 To UBound(arrLine)
        
            V1(i, j) = arrLine(j)
            
        Next j
        i = i + 1
    Loop
 
Close #1
    RR.Value = V1
    Debug.Print Round(Timer - T, 2)
Exit Sub
err:
MsgBox "ファイルのインポートに失敗しました", vbCritical
End Sub

Function count_txt_Row(TargetFile As String)

    Dim FSO As Object
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    With FSO.OpenTextFile(TargetFile, 8)
        count_txt_Row = .Line
        .Close
    End With
    Set FSO = Nothing
    
End Function

Function count_txt_Col(strPath As String)

Open strPath For Input As #1

        Line Input #1, strLine
        arrLine = Split(strLine, ",")
        count_txt_Col = UBound(arrLine)
 
Close #1
End Function
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?