티스토리 뷰

반응형

Excel VBA로 MSWORD를 실행시키고, 문서를 추가한 후, 글자를 쓰는 예제를 만들어보았다.

 

개념을 정리해보면

MSWORD 프로그램을 가르키는 객체 변수, WordApp를 선언하고,

MSWORD에 새문서를 추가하여 WordDoc 변수를 선언한 후,

글자는 WordApp에 입력을 한다.

 

Ms Word 에 문서를 추가하고 글씨를 쓰는 예제

 

여기서, "WordApp.Selection.TypeParagraph"는 엔터키(줄바꿈)를 치는 것과 같은 효과이다.

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

' Word 변수 객체 선언
'
Dim WordApp As New Word.Application ' Word 문서를 객체로 설정
WordApp.Visible = True              'New Apps will be hidden by default, so make visible

' 신규 문서 추가
Dim WordDoc As New Word.Document
Set WordDoc = WordApp.Documents.Add(Template:="Normal")

'write the value to the document
WordApp.Selection.TypeText Text:="TEST LINE1"
'move to the next line
WordApp.Selection.TypeParagraph
'move to the next line
WordApp.Selection.TypeParagraph
'write the value to the document
WordApp.Selection.TypeText Text:="TEST LINE2"
'move to the next line
WordApp.Selection.TypeParagraph


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

End Sub

 

매크로 실행 결과

 

 

 

 

 

 

 

댓글