つらつら Excel VBA

私の備忘録です。

カレントディレクトリの変更とファイル選択ダイアログの表示場所

Private Sub readLineTextFile()

Dim fType As String, promptText As String, chDirPath As String
Dim fPath As Variant
Dim buf As String

'カレントディレクトリを移動
curDirPath = CurDir
ChDir ActiveWorkbook.Path

fType = "テキストファイル (*.txt),*.txt"
promptText = "テキストファイルを選択して下さい"
fPath = Application.GetOpenFilename(fType, , promptText) 'ファイル選択ダイアログ表示

ChDir curDirPath '元に戻す

'ダイアログでキャンセルボタン選択時は処理を終了
If fPath = False Then End


On Error GoTo err_rtn
Open fPath For Input As #1
Do Until EOF(1)
Line Input #1, buf
'1行ずつ読み込んで何かしらの処理
Loop
err_rtn:
Close #1

End Sub