티스토리 뷰

반응형

Excel 매크로를 이용하여 Ms Word를 신규로 생성하는 것과, 기존 파일을 여는 방법 2가지로 정리하였다.

 

Ms Word 신규 생성
Sub CreateWordDocument()			' Word 문서 새로 생성하기

' Word 변수 객체 선언
' 아래 둘중 하나를 사용
'
' (1) dim / set 각각 별도 정의
Dim WordApp As Word.Application		' Word 변수 선언
Set WordApp = New Word.Application	' Word 문서를 객체로 설정
' (2) dim / set 을 한번꺼번에 정의
Dim WordApp As New Word.Application ' Word 문서를 객체로 설정

' 신규 문서 추가
Dim WordDoc As New Word.Document
Set WordDoc = WordApp.Documents.Add (Template:="Normal", NewTemplate:=False, DocumentType:=0)
WordApp.Visible = True 				'New Apps will be hidden by default, so make visible

' MS Word 닫기
WordApp.Quit

' 매크로가 끝났을 때, 컴퓨터의 메모리를 관리하기위해 word 객체를 제거한다
Set WordApp = Nothing 				'release the memory
Set WordDoc = Nothing 				'release the memory

End Sub

 

Ms Word 기존 파일 열기
Sub OpenWordDocument()			' 기존 Word 문서 새로 생성하기

' Word 변수 객체 선언
' 아래 둘중 하나를 사용
'
' (1) dim / set 각각 별도 정의
Dim WordApp As Word.Application		' Word 변수 선언
Set WordApp = New Word.Application	' Word 문서를 객체로 설정
' (2) dim / set 을 한번꺼번에 정의
Dim WordApp As New Word.Application ' Word 문서를 객체로 설정

Dim sdirectory = "C:\Users\DT168\Desktop\KTW\test.docx"	' 저장된 문서 경로 설정

' 저장된 문서 열기
Dim WordDoc As New Word.Document
Set WordDoc = WordApp.documents.Open(sdirectory, False)	' True : read-only (읽기전용)

WordApp.Visible = True				' Word 보이기

' MS Word 닫기
WordApp.Quit

' 매크로가 끝났을 때, 컴퓨터의 메모리를 관리하기위해 word 객체를 제거한다
Set WordApp = Nothing 				'release the memory
Set WordDoc = Nothing 				'release the memory

End Sub

 

Ms Word 저장 (Save)

Save with change를 true로 설정하고, 파일을 닫으면 저장이 된다.아래와 같이 WordDoc 객체에 With 명령어를 사용하여 코딩하는 방법과 WordDoc"." 을 이용하여 코딩하는 방법이 있으니, 편한 방법을 선택하여 코딩한다.

' 방법1
With WordDoc
    'save & close
    .Close SaveChanges:=True
End With

' 방법2
'save & close
WordDoc.Close SaveChanges:=True

 

Ms Word 저장 (SaveAs)
' Save file with new extension 
'
' strDocName은 파일의 저장경로와 파일명  "c:/Documents/example.docx"
'
WordDoc.SaveAs (strDocName)

 

 

 

 

 

 

 

 

 

 

 

댓글