VBA 엑셀 파일 복사, 초보자도 쉽게 따라 하기

엑셀 작업시 파일을 복사해야 하는 경우가 종종 발생합니다. 단순히 파일을 복사하는 것은 쉽지만,

VBA를 활용하면 복사 과정을 자동화 할 수 있습니다. 

 

샘플코드를 사용하면 특정파일을 엑세 시트에 명시된 명으로 자동으로 파일 복사를 수행합니다. 

 

Sub procFileCopy()

     Dim iChoice As Integer

     Dim strPath As String

     Dim sRow As Integer

     Dim eRow As Integer

     Dim eCol As Integer

     Dim index As Integer

     Dim tarPath As String

     Dim szTargetFileName As String

     Dim szFilenamePrefix As String

     tarPath = InputBox("경로를 입력하세요") '파일을 저장할 위치

     szFilenamePrefix = "C:\User\iser\Desktop\ssun\"

 

     Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

 

     iChoice = Application.FileDialog(msoFileDialogOpen).Show

 

     If iChoice <> o Then

          strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

          MsgBox strPath

     End If

     Sheets("Sheet1").Activate '복사될 파일명이 나열된 엑셀 시트명

 

     sRow = Selection.Row

     eRow = Selection.Row + Selection.Row.Count - 1

     sCol = Selection.Column

 

     For index = 1 To Selection.Rows.Count

          szTargetFileName = szFilenamePrefix & Cells(sRow + index - 1, sCol)

          VBA.FileCopy strPath, szTargetFileName

     Next

 

End Sub