テキストファイルを読む場合の例はを示す。
下記の例は、ダイアログボックスを開き、ファイル名を取得した後、
行数をカウントした後、
1バイトめに戻し、
再度、1行ずつ読み、セルの1列めに表示するとともに、
Ln()という文字列配列に読み込んでいる。
Sub TxtRead()
'テキストファイル名を取得する
Dim FilDlg As FileDialog
Dim PasNom As String
Dim TxtNom As String
Dim Ln() As String
Dim ir As Long
Dim jCncel As Integer
PasNom = ThisWorkbook.Path
If Right(PasNom, 1) <> "\" Then PasNom = PasNom & "\"
TxtNom = PasNom & "test.txt"
jCncel = 0
Set FilDlg = Application.FileDialog(msoFileDialogOpen)
With FilDlg
With .Filters
.Clear
.Add "txt(テキスト)", "*.txt", 1
End With
.InitialFileName = TxtNom
If .Show = True Then
TxtNom = .SelectedItems(1)
Else
MsgBox "cancelが選択されたため中止します"
jCncel = 1
End If
End With
Set FilDlg = Nothing
If jCncel <> 1 Then
'セルのクリアー
With ActiveSheet.UsedRange
Range(Cells(1,1),Cells(.Rows.Count, _
.Columns.Count)).clear
End With
ReDim Ln(1 To 1)
Open TxtNom For Input As #1
'行数をカウント(空読み)
ir = 0
Do Until EOF(1)
ir = ir + 1
Line Input #1, Ln(1)
Loop
'テキストファイルの読み込み
ReDim Ln(1 To ir)
Seek #1, 1
ir = 0
Do Until EOF(1)
ir = ir + 1
Line Input #1, Ln(ir)
Cells(ir, 1)
Loop
Close #1
End If
End Sub