엑셀 VBA 매크로로 CSV파일을 출력하는 방법을 알아보겠습니다.
소스 코드에 간단하게 주석을 달아놨습니다.
따로 소스 코드 설명은 하지 않도록 하겠습니다.
출력 형식의 구분자는 콤마(,)로 지정하였습니다.
문자 코드는 따로 지정하지 않았습니다.
문자 코드를 UTF-8로 지정한 소스 코드는 다른 포스팅에 올리도록 하겠습니다.
Sub CSV()
	Dim fileDate As String
	Dim maxRow As Long
	Dim maxCol As Long
	Dim iCount As Long
	Dim jCount As Long
	Dim stream
	Dim streamTmp
	Dim buf As String
	'현재 날짜 및 시간 취득
	fileDate = Format(Now, "_YYYYMMDDHHNNSS")
	'마지막 행 취득
	maxRow = ActiveSheet.Range("A1").End(xlDown).Row
	'마지막 열(컬럼) 취득
	maxCol = ActiveSheet.Range("A1").End(xlToRight).Column
	'파일을 저장할 경로 지정
	Dim FolderName As String
	'매크로 파일이 있는 폴더 안에 csv폴더를 만들도록 지정 
	FolderName = ActiveWorkbook.Path & "\csv"
	'지정한 경로에 폴더가 없는 경우에만 생성
	If Dir(FolderName, vbDirectory) = "" Then 
		MkDir FolderName
	End If
	'저장할 파일명 설정
	Dim strFilePath As String
	strFilePath = FolderName & "\csv" & fileDate & ".csv"
	Set stream = CreateObject("ADODB.Stream")
	With stream
		.Open
		For iCount = 1 To maxRow
			For jCount = 2 To maxCol - 1
				buf = buf & Cells(iCount, jCount) & ","
				kCount = jCount
			Next jCount
			buf = buf & Cells(iCount, kCount + 1) & vbCrLf
		Next iCount
		.WriteText buf, adWriteLin
		.savetofile strFilePath, 2
		.Close
	End With
	MsgBox ("CSV파일을 생성했습니다." & vbLf & vbLf & varFile)
End Sub
궁금한 내용이나 잘못된 곳이 있으면 코멘트 남겨주세요.
감사합니다.
 
 


댓글