엑셀 VBA에서는 파일을 생성, 열기, 읽기, 쓰기, 복사, 삭제, 이동 등의 작업을 수행할 수 있습니다.
이를 위해 FileSystemObject(FSO), Open 문, Workbook 개체 등을 활용합니다.
1. 파일 존재 여부 확인
Sub 파일_존재여부()
Dim filePath As String
filePath = "C:\Users\Desktop\test.txt"
If Dir(filePath) <> "" Then
MsgBox "파일이 존재합니다!"
Else
MsgBox "파일이 없습니다."
End If
End Sub
|
📌 Dir(파일경로) 함수를 사용하여 파일이 존재하는지 확인.
2. 파일 생성 및 쓰기
Sub 파일_생성_쓰기()
Dim filePath As String
Dim fileNum As Integer
filePath = "C:\Users\Desktop\test.txt"
fileNum = FreeFile ' 사용 가능한 파일 번호 할당
Open filePath For Output As #fileNum ' 파일 생성 (쓰기 모드)
Print #fileNum, "Hello, VBA!" ' 파일에 텍스트 쓰기
Close #fileNum ' 파일 닫기
MsgBox "파일이 생성되었습니다!"
End Sub
|
📌 Open ... For Output As #n → 파일 생성 후 쓰기 모드로 열기
📌 Print #n, "내용" → 파일에 데이터 저장
📌 Close #n → 파일 닫기
3. 파일 읽기
Sub 파일_읽기()
Dim filePath As String
Dim fileNum As Integer
Dim textLine As String
filePath = "C:\Users\Desktop\test.txt"
fileNum = FreeFile ' 사용 가능한 파일 번호 할당
Open filePath For Input As #fileNum ' 파일 읽기 모드로 열기
Do While Not EOF(fileNum) ' 파일 끝까지 읽기
Line Input #fileNum, textLine
Debug.Print textLine ' 즉시 실행 창에 출력
Loop
Close #fileNum ' 파일 닫기
End Sub
|
📌 Open ... For Input As #n → 파일 읽기 모드로 열기
📌 Line Input #n, 변수 → 한 줄씩 읽기
📌 EOF(n) → 파일 끝(End Of File) 체크
4. 파일 추가 쓰기 (Append)
Sub 파일_추가쓰기()
Dim filePath As String
Dim fileNum As Integer
filePath = "C:\Users\Desktop\test.txt"
fileNum = FreeFile ' 사용 가능한 파일 번호 할당
Open filePath For Append As #fileNum ' 기존 파일에 추가 쓰기
Print #fileNum, "새로운 내용 추가!"
Close #fileNum ' 파일 닫기
End Sub
|
📌 Open ... For Append → 기존 파일의 내용 유지하면서 추가 쓰기
5. 파일 복사
Sub 파일_복사()
FileCopy "C:\Users\Desktop\test.txt", "C:\Users\Desktop\backup.txt"
MsgBox "파일이 복사되었습니다!"
End Sub
|
📌 FileCopy "원본", "복사본" → 파일 복사
6. 파일 이동 (이름 변경)
Sub 파일_이동()
Name "C:\Users\Desktop\test.txt" As "C:\Users\Documents\test.txt"
MsgBox "파일이 이동되었습니다!"
End Sub
|
📌 Name "원래위치" As "새위치" → 파일 이름 변경 또는 이동
7. 파일 삭제
Sub 파일_삭제()
Dim filePath As String
filePath = "C:\Users\Desktop\test.txt"
If Dir(filePath) <> "" Then
Kill filePath ' 파일 삭제
MsgBox "파일이 삭제되었습니다!"
Else
MsgBox "삭제할 파일이 없습니다!"
End If
End Sub
|
📌 Kill "파일경로" → 파일 삭제
8. 파일 선택 대화상자 (Application.GetOpenFilename)
Sub 파일_선택_열기()
Dim filePath As String
filePath = Application.GetOpenFilename("텍스트 파일 (*.txt), *.txt")
If filePath <> "False" Then
MsgBox "선택한 파일: " & filePath
Else
MsgBox "파일을 선택하지 않았습니다."
End If
End Sub
|
📌 Application.GetOpenFilename → 파일 선택 대화상자 표시
📌 If filePath <> "False" → 사용자가 파일을 선택했는지 확인
9. 폴더 선택 대화상자 (Application.FileDialog)
Sub 폴더_선택()
Dim dlg As FileDialog
Dim folderPath As String
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
If dlg.Show = -1 Then
folderPath = dlg.SelectedItems(1)
MsgBox "선택한 폴더: " & folderPath
Else
MsgBox "폴더를 선택하지 않았습니다."
End If
End Sub
|
📌 msoFileDialogFolderPicker → 폴더 선택 창 표시
📌 dlg.SelectedItems(1) → 선택한 폴더 경로 반환
10. 파일 목록 가져오기 (Dir 사용)
Sub 파일_목록_출력()
Dim filePath As String
filePath = Dir("C:\Users\Desktop\*.txt") ' 특정 확장자(.txt) 파일 목록 가져오기
Do While filePath <> ""
Debug.Print filePath ' 즉시 실행 창에 출력
filePath = Dir() ' 다음 파일 가져오기
Loop
End Sub
|
📌 Dir("경로\*.확장자") → 특정 폴더 내 파일 목록 검색
📌 Dir() → 다음 파일 검색
11. FileSystemObject (FSO) 활용
📌 FSO 객체 생성
Sub FSO_사용()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("C:\Users\Desktop\test.txt") Then
MsgBox "파일이 존재합니다!"
Else
MsgBox "파일이 없습니다!"
End If
End Sub
|
📌 CreateObject("Scripting.FileSystemObject") → FSO 객체 생성
📌 FileExists("경로") → 파일 존재 여부 확인
📝 정리
작업
|
방법
|
파일 존재 여부 확인
|
Dir(파일경로) <> ""
|
파일 생성 & 쓰기
|
Open ... For Output & Print
|
파일 읽기
|
Open ... For Input & Line Input
|
파일 추가 쓰기
|
Open ... For Append
|
파일 복사
|
FileCopy "원본", "복사본"
|
파일 이동/이름 변경
|
Name "원래위치" As "새위치"
|
파일 삭제
|
Kill "파일경로"
|
파일 선택 창 열기
|
Application.GetOpenFilename
|
폴더 선택 창 열기
|
Application.FileDialog(msoFileDialogFolderPicker)
|
파일 목록 가져오기
|
Dir("경로\*.확장자")
|
FileSystemObject 사용
|
CreateObject("Scripting.FileSystemObject")
|
🔥 파일을 다루는 VBA 기능을 익히면, 엑셀 자동화를 더 강력하게 만들 수 있습니다! 🚀