반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

[VBA] Userform 만들기

2014. 2. 21. 23:28 | Posted by 솔웅


반응형

Userform


이 글에서는 Excel VBA Userform을 어떻게 생성하는지를 보여드립니다.
여기서는 아래와 같은 userform을 만들어 보겠습니다.

..




Add the Controls

Userform에 control들을 추가하려면 아래와 같이 하세요.

1. Visual Basic Editor를 연다. Project Explorer가 보이지 않으면 View-Project Explorer를 클릭한다.
2. Insert-Userform을 클릭한다. Toolbox가 자동으로 뜨지 않으면 View-Toolbox를 클릭한다.

여기까지 하면 아래와 같은 화면을 보실 수 있습니다.



3. 아래 테이블에 있는 control들을 추가 한다. 이 작업이 끝나면 위에서 본 것과 같은 Userform 모양이 될 것이다. 예를 들어 Toolbox에 있는 TextBox 를 클릭하면 text box control이 생성 될 것이다. 혹은 Userform에 text box를 드래그 할 수도 있다. Car를 할 경우 라디오버튼을 만들기 전에 frame 부터 만드는 것을 잊지 마세요.


4. 아래 테이블에 맞게 이름과 caption들을 바꾸자. Names는 Excel VBA code에서 사용될 것이다. Caption은 화면에 표시되는 글자를 말한다. control의 이름들을 바꾸어 보는 것도 좋은 연습이 될 것이다. 이렇게 바꾸면 코딩을 할 때 훨씬 편하게 할 수 있다. control의 name과 caption을 바꾸려면 View를 클릭하고 Properties 윈도우에서 각 control들을 클릭하면 된다.

Control Name Caption
Userform DinnerPlannerUserForm Dinner Planner
Text Box NameTextBox  
Text Box PhoneTextBox  
List Box CityListBox  
Combo Box DinnerComboBox  
Check Box DateCheckBox1 June 13th
Check Box DateCheckBox2 June 20th
Check Box DateCheckBox3 June 27th
Frame CarFrame Car
Option Button CarOptionButton1 Yes
Option Button CarOptionButton2 No
Text Box MoneyTextBox  
Spin Button MoneySpinButton  
Command Button OKButton OK
Command Button ClearButton Clear
Command Button CancelButton Cancel
7 Labels No need to change Name:, Phone Number:, etc.



Note: combo box는 유저가 아이템을 선택할 수 있는 drop down 리스트 입니다. 한개의 옵션만 선택될 수 있습니다.

Show the Userform

Userform을 보이려면 worksheet에 command button을 만들고 아래 코드를 실행하세요.

Private Sub CommandButton1_Click()
    DinnerPlannerUserForm.Show
End Sub



이제 Sub UserForm_Initialize를 생성할 겁니다. 이 Userform에 대해 Show 메소드를 사용할 때 이 sub 도 자동적으로 실행될 겁니다.

1. Visual Basic Editor를 연다.
2. Project Explorer에서 DinnerPlannerUserForm을 마우스 오른쪽 클릭을 하고 View Code를 선택한다.
3. left drop-down list에서 Userform을 선택한다. right drop-down list 에서 Initialize를 선택한다.
4. 아래 코드를 복사해 넣는다.

Private Sub UserForm_Initialize()

'Empty NameTextBox
NameTextBox.Value = ""

'Empty PhoneTextBox
PhoneTextBox.Value = ""

'Empty CityListBox
CityListBox.Clear

'Fill CityListBox
With CityListBox
    .AddItem "San Fransisco"
    .AddItem "Oakland"
    .AddItem "Richmond"
End With

'Empty DinnerComboBox
DinnerComboBox.Clear

'Fill DinnerComboBox
With DinnerComboBox
    .AddItem "Italian"
    .AddItem "Chinese"
    .AddItem "Frites and Meat"
End With

'Uncheck DataCheckBoxes

DateCheckBox1.Value = False
DateCheckBox2.Value = False
DateCheckBox3.Value = False

'Set no car as default
CarOptionButton2.Value = True

'Empty MoneyTextBox
MoneyTextBox.Value = ""

'Set Focus on NameTextBox
NameTextBox.SetFocus

End Sub



텍스트 박스들은 비어 있을 겁니다. 리스트 박스하고 콤보박스는 채워져 있을 거구요. 체크박스들은 체크되어있지 않을 겁니다.


Assign the Macros

이제 Userform의 첫번째 파트를 만들었습니다. 이제 보기 좋아졌죠? 하지만 Userform 내의 어떤 버튼을 클릭하던지 아직 어떤 일이 일어나지는 않습니다.

1. Visual Basic Editor를 연다.
2. Project Explorer 에서 DinnerPlannerUserForm을 더블클릭한다.
3. Money spin button을 더블 클릭한다.
4. 아래 코드를 추가한다.

Private Sub MoneySpinButton_Change()

MoneyTextBox.Text = MoneySpinButton.Value

End Sub



이 코드는 spin button을 이용할 때 text box가 update 되도록 하는 부분입니다.

5. OK 버튼을 더블클릭한다.
6. 아래의 코드를 추가한다.

Private Sub OKButton_Click()

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Cells(emptyRow, 1).Value = NameTextBox.Value
Cells(emptyRow, 2).Value = PhoneTextBox.Value
Cells(emptyRow, 3).Value = CityListBox.Value
Cells(emptyRow, 4).Value = DinnerComboBox.Value

If DateCheckBox1.Value = True Then Cells(emptyRow, 5).Value = DateCheckBox1.Caption

If DateCheckBox2.Value = True Then Cells(emptyRow, 5).Value = Cells(emptyRow, 5).Value & " " & DateCheckBox2.Caption

If DateCheckBox3.Value = True Then Cells(emptyRow, 5).Value = Cells(emptyRow, 5).Value & " " & DateCheckBox3.Caption

If CarOptionButton1.Value = True Then
    Cells(emptyRow, 6).Value = "Yes"
Else
    Cells(emptyRow, 6).Value = "No"
End If

Cells(emptyRow, 7).Value = MoneyTextBox.Value

End Sub



우선 Sheet1을 Activate 하고 emptyRow 를 찾습니다. emptyRow 변수는 첫번째 빈 row입니다 그리고 기록이 될 때마다 하나씩 증가하게 됩니다. 그리고 나서 하는 일이 Userform에 있는 데이터를 emptyRow의 특정 컬럼에 옮겨 놓는 작업입니다.

7. Clear button을 더블클릭한다.
8. 아래의 코드를 추가한다.

Private Sub ClearButton_Click()

Call UserForm_Initialize

End Sub



이 라인은 Clear button이 클릭 됐을 때 Sub UserForm_Initialize를 call 하게 됩니다.

9. Cancle Button을 더블클릭한다.
10. 아래 코드를 추가한다.

Private Sub CancelButton_Click()

Unload Me

End Sub



이 코드는 Cancel button을 클릭했을 때 Userform을 닫도록 합니다.


Test the Userform

Visual Basic Editor를 나갑니다. 아래 처럼 Column 제목을 달고 form 에 내용을 입력한 다음에 OK 버튼을 눌러보세요.

Result:


원문을 보려면 여기를 클릭하세요.



반응형