10월 7 2015
봉하마을 …
외근중 근처에 있어서 잠시 들른 봉하마을
10월 6 2015
http://www.clien.net/cs2/bbs/board.php?bo_table=lecture&wr_id=290227
(엑셀(EXCEL) – 엑셀(Excel)과 워드(Word)의 연동을 통한 사용자 정의 사전 구현)
팁으로 올렸던 것을 이왕이면 실제 사용할 수 있고 편하게 사용하고자 수정해서 올립니다.
기존 것은 단순히 Excel에서 입력하고 Word에서 조회만 가능해서 두 프로그램을 실행하여
추가, 삭제 등을 해야 했으나 이 업그레이드 버전은 엑셀 파일을 열지않고 Word에서 단어들을
바로 추가, 수정 및 영문을 번역 단어로 전체 대치를 할 수 있도록 수정했습니다.
그리고 단어를 선택해서 바로 유저폼에서 조회할 수 있도록 하였습니다. 오른쪽 버튼을 누르면
팝업 메뉴를 구현(이것은 구걸…)하여 편의성을 올렸습니다. 일반적인 직장인?분이 MySQL이나
기타 DataBase프로그램을 이용하면 쉬울 것이라고 하지 말아주세요. 몰라서 안하는 것이 아니라
순수하게 Office Suite를 이용해서 이런 것도 할 수 있다는 것을 보여주는 것이기 때문입니다.
단어 대치 기능은 개별로 선택된 단어를 대치할 수도 있고 아래 붉은 글씨의 주의사항대로
문서 전체에서 등록된 단어들로 대치하는 기능입니다. 되돌릴 수 없는 기능이니 주의하세요.
쓰다 보니 되돌리기 기능이 너무 쉬워서 추가했습니다 ㅠㅠ.
Option Explicit
Private Sub CommandButton1_Click()
Dim i As Long
Dim fstr As String, sqlstr As String
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sConnString As String
‘ 연결 문자열 : Excel 2003
sConnString = “Provider=Microsoft.Jet.OLEDB.4.0;excel 8.0;DATABASE=C:\UserDic.xls;”
‘ 새로운 연결과 레코드셋 설정
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
‘ 연결
conn.Open sConnString
If Len(UserForm1.TextBox1.Text) = 0 Then Exit Sub
fstr = “%” & UserForm1.TextBox1.Text & “%”
sqlstr = “select Word, Trans, Mean from [DicList$] where Word like ‘” & fstr & “‘”
Set rst = conn.Execute(sqlstr)
‘ 데이터 체크
‘ 없으면 서브루틴 빠져 나감
If rst.BOF Or rst.EOF Then
UserForm1.ListBox1.Clear
Exit Sub
End If
rst.MoveFirst
i = 0
With UserForm1.ListBox1
.Clear
Do
.AddItem
.List(i, 0) = rst!Word
.List(i, 1) = rst!Trans
.List(i, 2) = rst!Mean
i = i + 1
rst.MoveNext
Loop Until rst.EOF
End With
‘ 연결 끊기와 메모리 비움
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rst = Nothing
End Sub
Private Sub CommandButton2_Click()
Dim i As Long
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sConnString As String
‘ 연결 문자열 : Excel 2003
sConnString = “Provider=Microsoft.Jet.OLEDB.4.0;excel 8.0;DATABASE=C:\UserDic.xls;”
‘ 새로운 연결과 레코드셋 설정
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
‘ 연결
conn.Open sConnString
Set rst = conn.Execute(“select Word, Trans, Mean from [DicList$] “)
‘ 데이터 체크
‘ 없으면 서브루틴 빠져 나감
If rst.BOF Or rst.EOF Then Exit Sub
rst.MoveFirst
i = 0
With UserForm1.ListBox1
.Clear
Do
.AddItem
.List(i, 0) = rst!Word
.List(i, 1) = rst!Trans
.List(i, 2) = rst!Mean
i = i + 1
rst.MoveNext
Loop Until rst.EOF
End With
‘ 연결 끊기와 메모리 비움
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rst = Nothing
‘ 검색할 값 초기화
TextBox1.Text = “”
TextBox2.Text = “”
TextBox3.Text = “”
End Sub
Private Sub CommandButton3_Click()
Dim sqlstr As String, fstr As String
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sConnString As String
‘ 연결 문자열 : Excel 2003
sConnString = “Provider=Microsoft.Jet.OLEDB.4.0;excel 8.0;DATABASE=C:\UserDic.xls;”
‘ 새로운 연결과 레코드셋 설정
Set conn = New ADODB.Connection
‘ 연결
conn.Open sConnString
fstr = Trim(UserForm1.TextBox1.Text)
If Len(fstr) = 0 Then Exit Sub
sqlstr = “SELECT * FROM [DicList$] WHERE Word='” & fstr & “‘”
Set rst = conn.Execute(sqlstr)
If rst.BOF Or rst.EOF Then
‘ 데이터 추가
sqlstr = “INSERT INTO [DicList$] VALUES (‘” & TextBox1.Text & “‘,'” &
TextBox2.Text & “‘,'” & TextBox3.Text & “‘)”
Call conn.Execute(sqlstr)
Else
MsgBox “동일 단어가 있습니다”
End If
‘ 연결 끊기와 메모리 비움
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
TextBox1.Text = “”
TextBox2.Text = “”
TextBox3.Text = “”
Call CommandButton2_Click
End Sub
Private Sub CommandButton4_Click()
Dim sqlstr As String, fstr As String, frstr As String
Dim tstr As String, mstr As String
Dim conn As ADODB.Connection
Dim sConnString As String
‘ 연결 문자열 : Excel 2003
sConnString = “Provider=Microsoft.Jet.OLEDB.4.0;excel 8.0;DATABASE=C:\UserDic.xls;”
‘ 새로운 연결과 레코드셋 설정
Set conn = New ADODB.Connection
‘ 연결
conn.Open sConnString
fstr = UserForm1.ListBox1.List(UserForm1.ListBox1.ListIndex, 0)
If Len(fstr) = 0 Then
MsgBox “단어를 선택하세요”
Exit Sub
End If
‘ 데이터 수정
frstr = UserForm1.TextBox1.Text
tstr = UserForm1.TextBox2.Text
mstr = UserForm1.TextBox3.Text
sqlstr = “UPDATE [DicList$] SET Trans = ‘” & tstr & “‘” & ” , Mean = ‘” & mstr & “‘” & ”
WHERE Word = ‘” & fstr & “‘”
Call conn.Execute(sqlstr)
‘ 디비를 변형적으로 업데이트
sqlstr = “UPDATE [DicList$] SET Word = ‘” & frstr & “‘” & ” WHERE Trans = ‘” & tstr &
“‘” & ” AND Mean = ‘” & mstr & “‘”
Call conn.Execute(sqlstr)
‘ 연결 끊기와 메모리 비움
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
TextBox1.Text = “”
TextBox2.Text = “”
TextBox3.Text = “”
Call CommandButton2_Click
End Sub
‘ 개별 단어 대치
Private Sub CommandButton5_Click()
Dim myRange As Range
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:=UserForm1.TextBox1.Text, MatchCase:=True,
MatchWholeWord:=True, _
ReplaceWith:=UserForm1.TextBox2.Text, Replace:=wdReplaceAll
End Sub
‘ 사전에 등록된 단어 전체 대치
Private Sub CommandButton6_Click()
Dim i As Integer
Dim myRange As Range
Set myRange = ActiveDocument.Content
For i = 0 To UserForm1.ListBox1.ListCount – 1
myRange.Find.Execute FindText:=UserForm1.ListBox1.List(i, 0), MatchCase:=True,
MatchWholeWord:=True, _
ReplaceWith:=UserForm1.ListBox1.List(i, 1), Replace:=wdReplaceAll
Next i
End Sub
‘ 사전에 등록된 단어 전체 환원
Private Sub CommandButton7_Click()
Dim i As Integer
Dim myRange As Range
Set myRange = ActiveDocument.Content
For i = 0 To UserForm1.ListBox1.ListCount – 1
myRange.Find.Execute FindText:=UserForm1.ListBox1.List(i, 1), MatchCase:=True,
MatchWholeWord:=True, _
ReplaceWith:=UserForm1.ListBox1.List(i, 0), Replace:=wdReplaceAll
Next i
End Sub
Private Sub ListBox1_Click()
TextBox1.Text = ListBox1.List(ListBox1.ListIndex, 0)
TextBox2.Text = ListBox1.List(ListBox1.ListIndex, 1)
TextBox3.Text = ListBox1.List(ListBox1.ListIndex, 2)
Call CopyToClip
End Sub
Module 하나를 추가해서 붙여넣기 합니다.
Option Explicit
Sub CopyToClip()
Dim obj As New DataObject
Dim Cliptxt As String
Cliptxt = UserForm1.ListBox1.List(UserForm1.ListBox1.ListIndex, 1)
obj.SetText Cliptxt
obj.PutInClipboard
End Sub
Sub Open_UserDic()
UserForm1.Show vbModeless
‘ 선택된 단어의 마지막 스페이스 문자 제거
UserForm1.TextBox1.Text = Trim(Selection.Text)
Dim i As Long
Dim fstr As String, sqlstr As String
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sConnString As String
‘ 연결 문자열 : Excel 2003
sConnString = “Provider=Microsoft.Jet.OLEDB.4.0;excel 8.0;DATABASE=C:\UserDic.xls;”
‘ 새로운 연결과 레코드셋 설정
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
‘ 연결
conn.Open sConnString
If Len(UserForm1.TextBox1.Text) = 0 Then Exit Sub
fstr = “%” & UserForm1.TextBox1.Text & “%”
sqlstr = “select Word, Trans, Mean from [DicList$] where Word like ‘” & fstr & “‘”
Set rst = conn.Execute(sqlstr)
‘ 데이터 체크
‘ 없으면 서브루틴 빠져 나감
If rst.BOF Or rst.EOF Then
UserForm1.ListBox1.Clear
UserForm1.TextBox2.Text = “”
UserForm1.TextBox3.Text = “”
Exit Sub
End If
rst.MoveFirst
i = 0
With UserForm1.ListBox1
.Clear
Do
.AddItem
.List(i, 0) = rst!Word
.List(i, 1) = rst!Trans
.List(i, 2) = rst!Mean
i = i + 1
rst.MoveNext
Loop Until rst.EOF
End With
‘ 연결 끊기와 메모리 비움
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rst = Nothing
End Sub
Sub BuildControls()
Dim oBtn As CommandBarButton
Dim oPopUp As CommandBarPopup
Dim oCtr As CommandBarControl
‘Make changes to the Normal template
CustomizationContext = NormalTemplate
‘Prevent double customization
Set oPopUp = CommandBars.FindControl(Tag:=”custPopup”)
If Not oPopUp Is Nothing Then GoTo Add_Individual
‘Add PopUp menu control to the top of the “Text” short-cut menu
Set oPopUp = CommandBars(“Text”).Controls.Add(msoControlPopup, , , 1)
With oPopUp
.Caption = “추가 기능”
.Tag = “custPopup”
.BeginGroup = True
End With
Set oBtn = oPopUp.Controls.Add(msoControlButton)
With oBtn
.Caption = “사용자 정의 사전”
.FaceId = 940
.Style = msoButtonIconAndCaption
.OnAction = “Open_UserDic”
End With
Set oBtn = Nothing
Add_Individual:
‘Or add individual commands directly to menu
Set oBtn = CommandBars.FindControl(Tag:=”custCmdBtn”)
If Not oBtn Is Nothing Then Exit Sub
‘Add control using built-in ID 758 (Boo&kmarks…)
Set oBtn = Application.CommandBars(“Text”).Controls.Add(msoControlButton, 758, , 2)
oBtn.Tag = “custCmdBtn”
If MsgBox(“This action caused a change to your Normal template.” _
& vbCr + vbCr & “Recommend you save those changes now.”, vbInformation +
vbOKCancel, _
“Save Changes”) = vbOK Then
NormalTemplate.Save
End If
Set oPopUp = Nothing
Set oBtn = Nothing
lbl_Exit:
Exit Sub
End Sub
Module 하나를 추가해서 붙여넣기 합니다. 코드가 충돌해서 Module을 분리하였습니다.
Option Explicit
Sub RemoveContent_MenuItem()
Dim oPopUp As CommandBarPopup
Dim oCtr As CommandBarControl
‘Make command bar changes in Normal.dotm
CustomizationContext = NormalTemplate
On Error GoTo Err_Handler
Set oPopUp = CommandBars(“Text”).Controls(“추가 기능”)
‘Delete individual commands on the PopUp menu
For Each oCtr In oPopUp.Controls
oCtr.Delete
Next
‘Delete the PopUp itself
oPopUp.Delete
‘Delete individual custom commands on the Text menu
For Each oCtr In Application.CommandBars(“Text”).Controls
If oCtr.Caption = “Boo&kmark…” Then
oCtr.Delete
Exit For
End If
Next oCtr
If MsgBox(“This action caused a change to your Normal template.” _
& vbCr + vbCr & “Recommend you save those changes now.”, vbInformation +
vbOKCancel, _
“Save Changes”) = vbOK Then
NormalTemplate.Save
End If
Set oPopUp = Nothing
Set oCtr = Nothing
Exit Sub
Err_Handler:
End Sub
추가> 문서 열고 닫을 때 사용자 정의 팝업 메뉴의 실행 및 제거 루틴이 빠졌어요.
저는 한 번 해서 계속 사용할 수 있어서 루틴을 깜빡 했습니다. 첨부된 화일에서 VBA Editor에서
ThisDocument 더블 클릭하시고 아래 코드 넣어세요.
Option Explicit
Private Sub Document_Close()
‘ 모듈이 오류가 나서 RemoveContentMenuItem를 RemoveContent_MenuItem로 바꾸세요.
Call RemoveContent_MenuItem
End Sub
Private Sub Document_Open()
Dim i As Long
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sConnString As String
Dim sqlstr As String
‘ 연결 문자열 : Excel 2003
sConnString = “Provider=Microsoft.Jet.OLEDB.4.0;excel 8.0;DATABASE=C:\UserDic.xls;”
‘ 새로운 연결과 레코드셋 설정
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
‘ 연결
conn.Open sConnString
Set rst = conn.Execute(“select Word, Trans, Mean from [DicList$] “)
‘ 데이터 체크
‘ 없으면 서브루틴 빠져 나감
If rst.BOF Or rst.EOF Then Exit Sub
rst.MoveFirst
i = 0
With UserForm1.ListBox1
.Clear
Do
.AddItem
.List(i, 0) = rst!Word
.List(i, 1) = rst!Trans
.List(i, 2) = rst!Mean
i = i + 1
rst.MoveNext
Loop Until rst.EOF
End With
‘ 연결 끊기와 메모리 비움
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rst = Nothing
‘ 사용자 정의폼을 모달리스 즉 플로팅 윈도우로 뛰어서
‘ 사용자가 수정,입력을 하면서 사전 참조할 수 있도록 함
UserForm1.Show vbModeless
‘ 사용자 편의를 위해 어짜피 영어 사전이므로 영어를 기본으로 입력하게 함
UserForm1.TextBox1.IMEMode = fmIMEModeAlpha
‘ 사용자 팝업 메뉴 생성
Call BuildControls
End Sub
수정 첨부 화일 : 20151006 – 워드(Word)의 연동을 통한 사용자 정의 사전 구현(기능 다수 추가)
By vinipapa • 무른모 • 0 • Tags: 사용자 정의 사전, 엑셀(EXCEL), 워드(Word), 팁
10월 8 2015
엑셀(EXCEL) – 각 행별로 셀 패턴별 숫자 합치기
데이터를 다룰 때 정형화되면 좋은데 아래의 질문처럼 정형화된 것도 안된 것도 아닌 질문이
올라오면 참 어떤 형식을 찾는데 힘이 듦니다. 질문에는 정형화된 것처럼 나오는데 만약에
각 열마다 크기가 달라지면 문제가 생깁니다. 물론 배열수식에서 범위를 최대한 넓혀 잡으면
되지만 VBA의 관점에서 보면 난감한 내용입니다.
http://www.clien.net/cs2/bbs/board.php?bo_table=kin&wr_id=3548380
(엑셀 매크로 질문 드립니다, 행별 특정 값 옆의 값 취합)
첨부의 그림과 같이 “X” 마크 옆의 값들을 취합하라는 내용입니다. 루틴은 간단합니다.
Option Explicit
Sub Sum_By_Mark()
Dim RngCel As Range, RngRow As Range
Dim i As Integer, rcnt As Integer
Dim Xsum As Long
Dim sht As Worksheet, tgt As Worksheet
Set sht = Sheets(“Data”)
sht.Select
‘ 취합할 데이터의 행의 수를 체크합니다.
rcnt = sht.Range(“A1”, Range(“A1”).End(xlDown)).Cells.Count
‘ 데이터 취합할 시트를 초기화 합니다.
For Each tgt In Worksheets
If tgt.Name = “X_Cnt_Row” Then
Application.DisplayAlerts = False
tgt.Delete
Application.DisplayAlerts = True
End If
Next
‘ 새 시트를 만듭니다.
Worksheets.Add.Name = “X_Cnt_Row”
‘ 행만큼 루프를 돌립니다.
For i = 1 To rcnt
‘ 영역을 열마다 재설정 합니다. 행의 제일 뒤에서 값이 나타날 때까지 취합니다.
Set RngRow = sht.Range(“B” & i, sht.Range(“B” & i).Offset(0, 256).End(xlToLeft))
‘ 취합할 데이터의 제목행을 새 시트로 옮깁니다
Sheets(“X_Cnt_Row”).Range(“A” & i).Value = RngRow.Offset(0, -1).Value
‘ 영역을 순환합니다.
For Each RngCel In RngRow
‘ 영역의 컬럼을 체크하여 필요없는 부분을 건너뜁니다.
If RngCel.Column / 2 <> 0 Then
‘ 영역과 비교하여 참값을 취하여 더해 줍니다
If UCase(RngCel.Offset(0, 1).Value) = “X” Then
Xsum = Xsum + RngCel.Value
End If
End If
Next RngCel
‘ 더해진 값을 취합 시트에 넣어줍니다.
Sheets(“X_Cnt_Row”).Range(“A” & i).Offset(0, 1).Value = Xsum
‘ 행의 더한 값을 초기화 시킵니다.
Xsum = 0
Next i
End Sub
주석 참고하시면 쉽게 이해하실 수 있을 것입니다. 만약에 “O” 마크를 찾고 싶으면 코드 중에서
if RngCel.Column / 2 <> 0 then 을 if RngCel.Column / 2 = 0 then로 바꾸시고 그 아래 코드를
If UCase(RngCel.Offset(0, 1).Value) = “X” Then의 “X”를 “O”로 바꾸시면 됩니다.
아래 코멘트처럼 간단하게 처리할 수도 있지만 VBA를 요청하셔서 올립니다.
첨부 화일 : 20151008-각 행별의 셀 패턴별 숫자 합치기
By vinipapa • 무른모 • 0 • Tags: 셀, 엑셀(EXCEL), 패턴, 합