Atlassian uses cookies to improve your browsing experience, perform analytics and research, and conduct advertising. Accept all cookies to indicate that you agree to our use of cookies on your device.
Atlassian uses cookies to improve your browsing experience, perform analytics and research, and conduct advertising. Accept all cookies to indicate that you agree to our use of cookies on your device. Atlassian cookies and tracking notice, (opens new window)
VBA는 Excel를 다루는 사용자에게 가장 유용하고 접근이 쉬운 개발언어로, 이를 이용하여 MIDAS-Civil API를 사용하는 방법을 알아보도록 하겠습니다.
(본 컨텐츠는 VBA, Json, Restfull API에 간단한 기본지식이 있는 분들이 유용하게 사용할 수 있도록 작성되었습니다.)
Json 다루기!
MIDAS-API에서 데이터교환은 Json format으로 이루어 지나, VBA에서는 Json format을 공식적으로 지원해주지 않습니다. 따라서, 아래와 같이 Dictionary Object와 JsonConverter Library를 이용하여 Json format을 작성합니다.
그럼 Dictionary Object와 JsonConverter가 무엇인지 알아볼까요?
Dictionary Object 란?
Dictionary Object는 VBA에서 사용할 수 있는 변수의 일종으로 Key : Item 형태로 쌍의 데이터를 가지는 객체입니다. 이와 관한 MS의 공식 설명은 아래 링크에서 확인할 수 있습니다.
Function WebRequest(Method As String, Command As String, Body As String) As String
Dim TCRequestItem As Object
Dim URL As String
Dim MAPIKey As Variant
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
'SetTimeouts(resolveTimeout, ConnectTimeout, SendTimeout, ReceiveTimeout)
TCRequestItem.SetTimeouts 200000, 200000, 200000, 200000
'Get MAPI-Key from Sheets
MAPIKey = Range("MAPIKey").Value
'URL & Commend
URL = "https://api-beta.midasit.com:443/civil" & Command
'Request API
TCRequestItem.Open Method, URL, False
TCRequestItem.SetRequestHeader "Content-type", "application/json"
TCRequestItem.SetRequestHeader "MAPI-Key", MAPIKey
TCRequestItem.Send Body
'API Response
WebRequest = TCRequestItem.ResponseText
End Function
MIDAS Civil 에서 Data를 얻어보자!
자, 이제 Civil 파일(Arch.mcb) 로부터 Node 정보를 받아온 후, Excel Sheet에 넣어보겠습니다.
“GET” Method로 /db/node의 정보를 요청합니다.
받아온 정보는 String 형태의 Json format으로, JsonConverter를 이용해 Dictionary Object에 할당합니다.
Dictionary 함수를 이용해 각 배열변수에 좌표 및 절점번호를 할당합니다.
할당된 배열변수를 엑셀시트에 출력합니다.
아래의 코드는 위에 설명을 기초적인 방법으로 구현한 것입니다. VBA에 경험이 많은 사용자라면 더욱 간결한 코드로 구현이 가능합니다.
Get Method (node)
Private Sub GetNode()
Dim dicNode As dictionary
Dim Response As String
'Get Node Inofrmation
Response = WebRequest("GET", "/db/node", "")
Debug.Print Response
'Parsing Data
Set dicNode = JsonConverter.ParseJson(Response)
Debug.Print "Check======================="
Debug.Print dicNode("NODE")("42")("X")
'Parsing Data
Dim i As Integer
Dim NodeID As Variant
Dim NbNode As Long
NbNode = dicNode("NODE").Count - 1
NodeID = dicNode("NODE").Keys
Dim NodeX(), NodeY(), NodeZ() As Double
ReDim NodeX(NbNode), NodeY(NbNode), NodeZ(NbNode)
For i = 0 To NbNode
NodeX(i) = dicNode("NODE")(NodeID(i))("X")
NodeY(i) = dicNode("NODE")(NodeID(i))("Y")
NodeZ(i) = dicNode("NODE")(NodeID(i))("Z")
Next i
With Sheet1
For i = 0 To NbNode
.Cells(5 + i, "B") = NodeID(i)
.Cells(5 + i, "C") = NodeX(i)
.Cells(5 + i, "D") = NodeY(i)
.Cells(5 + i, "E") = NodeZ(i)
Next i
End With
End Sub
Arch.mcb 로부터 “GET” 해보기
MIDAS Civil 에 Data를 보내보자!
위에 예제에서 알 수 있듯이 (직접실행창 확인) 절점 데이터는 아래와 같은 구조로 작성됩니다.
자 이제 절점정보가 어떤 포맷을 가지고 있는지 확인했으니, 새파일을 열고 엑셀에 입력된 절점 정보를 Civil로 보내 보겠습니다.
Sheet의 절점정보를 배열변수에 할당합니다.
배열변수를 Dictionary Object에 할당합니다.
Dctionary Object를 JsonConvert를 이용해 Json format의 String data로 변환합니다.
이를 Post Method를 이용해 Civil에 보내줍니다.
아래의 코드는 위에 설명을 구현한 것입니다.
Post Method (node)
Private Sub PostNode()
Dim i As Integer
Dim NodeInfo As Variant
Dim dicMain As Dictionary
Dim dicNdID As Dictionary
Dim dicCoor As Dictionary
Dim strBody As String
Dim Response As String
NodeInfo = Sheet1.Range(Cells(5, "B"), Cells(60, "E")).Value
Set dicMain = New Dictionary: Set dicNdID = New Dictionary
For i = 1 To UBound(NodeInfo)
Set dicCoor = New Dictionary 'Create
dicCoor.Add "X", NodeInfo(i, 2)
dicCoor.Add "Y", NodeInfo(i, 3)
dicCoor.Add "Z", NodeInfo(i, 4)
dicNdID.Add NodeInfo(i, 1), dicCoor
Set dicCoor = Nothing 'Release
Next i
dicMain.Add "Assign", dicNdID
strBody = JsonConverter.ConvertToJson(dicMain)
Debug.Print strBody
Response = WebRequest("POST", "/db/node", strBody)
Debug.Print Response
End Sub
새파일에 “POST” 해보기
MIDAS Civil 에 Data를 수정해보자!
자 마지막으로 새파일에 입력된 절점을 직선의 형태로 바꿔보겠습니다.
우선, Excel 데이터를 1m 간격의 직선 형태로 바꾼 후, 위에서 사용한 코드를 그대로 복사한 후 WebReqeust Fuction의 Method만 PUT으로 교체해서 작동시켜보겠습니다.
Put Method (node)
Dim i As Integer
Dim NodeInfo As Variant
Dim dicMain As Dictionary
Dim dicNdID As Dictionary
Dim dicCoor As Dictionary
Dim strBody As String
Dim Response As String
NodeInfo = Sheet1.Range(Cells(5, "B"), Cells(60, "E")).Value
Set dicMain = New Dictionary: Set dicNdID = New Dictionary
For i = 1 To UBound(NodeInfo)
Set dicCoor = New Dictionary 'Create
dicCoor.Add "X", NodeInfo(i, 2)
dicCoor.Add "Y", NodeInfo(i, 3)
dicCoor.Add "Z", NodeInfo(i, 4)
dicNdID.Add NodeInfo(i, 1), dicCoor
Set dicCoor = Nothing 'Release
Next i
dicMain.Add "Assign", dicNdID
strBody = JsonConverter.ConvertToJson(dicMain)
Debug.Print strBody
Response = WebRequest("PUT", "/db/node", strBody)
Debug.Print Response
새파일에 “PUT” 해보기
위에서 살펴본 3가지(GET,POST,PUT)는 Civil-API에서 사용이 가능한 대표적인 동작 방식이며,
이를 Excel이라는 강력한 툴을 이용하여 사용한다면, 여러분이 상상하는 것을 만들어 낼 수 있다고 생각합니다.
이제부터는 더 유용한 사용을 위해 Dictionary Object에 대해 조금 더 얘기해 보고 마치겠습니다.
Dictionary Object 톺아보기
Dictionary는 Key:Item라는 쌍의 데이터를 가지는 변수입니다.
Key와 Item를 어떤 방식으로 사용할 수 있는지 예제를 통해 알아보도록 하겠습니다.
우선 Dictionary Object에 어떤 Function이 있는지 살펴보겠습니다.
Fuction
Example
Fuction
Example
item 더하기 (Key가 존재하면 안됩니다.)
dict.add Key, Value
(e.g. dict.add “Apples”, 50)
Item 수정하기 (만약, Key가 존재하지 않으면, 자동으로 더해줍니다.)
dict(Key) = Value
(e.g. dict(“Oranges”) = 60)
Key 값으로 Value 가져오기
Value= dict(Key)
(e.g. applecount = dict(“Apples”)
Key값이 존재하는지 확인하기
(return as boolean)
dict.Exists(Key)
(e.g. if dict.Exists(“Apples”) then)
Item 지우기
dict.Remove Key
e.g. dict.Remove “Apples”
모든 Item 지우기
dict.RemoveAll
Items 개수 가져오기
dict.Count
모든 Item을 확인하기 (for each loop)
Dim key As Variant
For Each key In dict.Keys
Debug.Print key, dict(key)
Next key
모든 Item을 확인하기 (for loop - early binding only)
Dim i As Long
For i = 0 to dict.Count - 1
Debug.Print dict.Keys(i), dict.Items(i)
Next i
모든 Item을 확인하기 (for loop - early and late binding only)
Dim i As Long
For i = 0 to dict.Count -1
Debug.Print dict.Keys()(i), dict.Items()(i)
Next i
Key 에서 대소문자를 구분하기 (Dictionary 는 비어져 있어야 합니다.) defalut입니다.
dict.CompareMode = vbBinaryCompare
Key 에서 대소문자를 구분하지 않기 (Dictionary 는 비어져 있어야 합니다.)
dict.CompareMode = vbTextCompare
모든 Key을 배열로 반환하기
Dim KeyValues as Variant
KeyValues = dict.Keys
모든 Item을 배열로 반환하기
Dim ItemValuesas Variant
ItemValues= dict.Items
Item 등록하고 출력하기
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "Apple", 50
dict.Add "Banana", 60
dict.Add "Orange", 100
Dim i As Long
For i = 0 To dict.Count - 1
Debug.Print dict.Keys(i), dict.Items(i)
Next i
Apple 50 Banana 60 Orange 100
Item 지우기
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "Apple", 50
dict.Add "Banana", 60
dict.Add "Orange", 100
dict.Remove "Banana"
Dim i As Long
For i = 0 To dict.Count - 1
Debug.Print dict.Keys(i), dict.Items(i)
Next i
Apple 50 Orange 100
특정Key의 Item값 확인하기
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "Apple", 50
dict.Add "Banana", 60
dict.Add "Orange", 100
If dict.Exists("Apple") Then
Debug.Print dict("Apple")
End If
50
Key,Items 값을 모두 배열로 반환하기
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "Apple", 50
dict.Add "Banana", 60
dict.Add "Orange", 100
Dim i As Integer
Dim KeyValues, ItemValues As Variant
KeyValues = dict.Keys
ItemValues = dict.Items
For i = 0 To UBound(KeyValues)
Debug.Print KeyValues(i), ItemValues(i)
Next i
Apple 50 Banana 60 Orange 100
단계 구조로 만들기
우선 Dictionary를 단계구조로 만들기 위해서는 Shallow/Deep Copy의 개념을 이해할 필요가 있습니다. Dictionary Object는 Shallow Copy를 기본으로 하기 때문입니다.
이를 이해하기 위해서 아래의 코드를 살펴봅니다.
Dim A As Double
Dim B As Double
'Assign Value at A
A = WorksheetFunction.PI()
'Assign A to B
B = A
'Print Results
Debug.Print "A : " & A
Debug.Print "B : " & B
'Modify B Value
B = 10.56548
'Print Results
Debug.Print "A : " & A
Debug.Print "B : " & B
A : 3.14159265358979 B : 3.14159265358979 A : 3.14159265358979 B : 10.56548
VBA에서 사용하는 대부분의 변수는 위와 같이 DeepCopy를 수행합니다. 즉, A와 B가 참조하는 메모리가 다르게 되므로, 복사한 이후로는 서로의 값에는 영향을 미치지 않습니다.
이를 Dictionary Object로 비슷하게 구현해보겠습니다.
Dim A As Dictionary
Dim B As Dictionary
'Assign Value at A
Set A = New Dictionary
A.Add "Apple", 50
A.Add "Banana", 60
A.Add "Orange", 100
'Assign A to B
Set B = A
'Print Results
Debug.Print "A : " & A("Apple")
Debug.Print "B : " & B("Apple")
'Modify B Value
B("Apple") = 30
'Print Results
Debug.Print "A : " & A("Apple")
Debug.Print "B : " & B("Apple")
A : 50 B : 50 A : 30 B : 30
18열에서 B의 “Apple”에 해당되는 값만 수정했지만, 그 영향은 A에도 적용됩니다. 즉, A와 B가 참조하는 메모리가 같습니다. 이것을 Shallow Copy라고 합니다. (같은 메모리를 다른 2개의 변수로 참조하고 있습니다.)
이 부분을 알아야 하는 이유는 변수관리가 있습니다.
예를 들어 5개의 Node를 Json 구조를 짠다고 가정해봅니다. 우선 X, Y, Z를 Key로 갖는 5개의 Dictionary가 필요합니다. 그리고 이 Dictionary를 Item으로 가지고, Node ID를 Key로 갖는 5개의 Dictionary 가 필요합니다. 마지막으로 이걸 “Assign”이라는 Key를 가지는 Dictionary 1개가 필요합니다.
5개의 소수의 Node 정보를 가지는 Json 구조를 만드는데 11개의 Dictionary 변수가 필요하게 됩니다.
이 부분을 해결하기 위해서는 첫번째로 생각할 수 있는 부분은 같은 변수를 계속해서 Copy 해서 쓰는 방법이 있지만, 위에서 살펴본 바와 같이 Dictionary Object는 Shallow Copy를 기본적으로 하기 때문에, 효율적이지 않습니다.
따라서, 아래와 같이 Dictionary 를 Create, Release를 반복하여 사용하는 것을 추천합니다.
Dim i As Integer
Dim ID, Xc, Yc, Zc As Variant
ID = Array(1, 2, 3, 4, 5)
Xc = Array(1, 2, 3, 4, 5)
Yc = Array(6, 7, 8, 9, 10)
Zc = Array(0, 0, 0, 0, 0)
Dim dicMain As Dictionary
Dim dicSub1 As Dictionary
Dim dicSub2 As Dictionary
Set dicMain = New Dictionary
Set dicSub1 = New Dictionary
For i = LBound(ID) To UBound(ID)
Set dicSub2 = New Dictionary 'Create
dicSub2.Add "X", Xc(i)
dicSub2.Add "Y", Yc(i)
dicSub2.Add "Z", Zc(i)
dicSub1.Add ID(i), dicSub2
Set dicSub2 = Nothing 'Release
Next i
dicMain.Add "Assign", dicSub1
Debug.Print JsonConverter.ConvertToJson(dicMain)