sourcetip

vba: 함수에서 사전 반환

fileupload 2023. 6. 7. 23:05
반응형

vba: 함수에서 사전 반환

이것은 제가 하려는 일의 개요입니다.

이것은 나에게 효과가 없고, 왜 그런지는 불분명합니다.

많은 도움을 주셔서 미리 감사드립니다.

        Sub mySub()
        dim myDict as Dictionary
            myDict=new Dictionary

                myDict=myFunc()

        End Sub

        Function myFunc()
            dim myDict2
                set myDict2 = new Dictionary

                    'some code that does things and adds to myDict2'

            myFunc=myDict2
        End Function

개체를 할당할 때마다 값 대신 SET 키워드를 사용해야 합니다.

    Sub mySub()
        dim myDict as Dictionary
        set myDict = myFunc()
    End Sub

    Function myFunc() as Dictionary
        dim myDict2 as Dictionary
        set myDict2 = new Dictionary
                'some code that does things and adds to myDict2'
        set myFunc=myDict2
    End Function

또한 원래 코드는 myDict를 새 Dictionary 개체로 만든 다음 즉시 다른 개체로 대체했습니다.그냥 그 단계를 건너뛸 수 있습니다.

저는 이것이 오래된 질문이라는 것을 압니다. 하지만 포스트 앤 솔루션이 제가 이 문제를 해결하는 데 도움이 되었고, 저는 다음 단계로 넘어갔습니다.그것은 작은 도약이었습니다.감사해요!

사전을 프로세스 이름과 ID로 채우는 함수를 변환하여 사전 객체를 반환하는 것은 어떻습니까?그런 다음 블로그에서 배운 사전 내용으로 시트를 채우는 간단한 작업입니다.저자 이름이 있으면 좋겠지만 링크가 포함되어 있습니다.

시트 1은 당연히 가정되었습니다.원하는 대로 사용자 지정합니다.다시 한 번 말씀드리지만, 이것은 두 분이 올린 글에서 조금 벗어난 것입니다.정말 멋진 작업이었습니다, 여러분, 감사합니다!

Sub Test_AllRunningApps()
    Dim apps As Dictionary
    Set apps = AllRunningApps()

    'Populate a sheet with a dictionary - http://exceldevelopmentplatform.blogspot.com/2018/05/vba-writing-dictionaries-to-worksheet.html
    Sheet1.Cells(1, 1).Resize(apps.Count, 1).Value2 = Application.Transpose(apps.Keys)
    Sheet1.Cells(1, 2).Resize(apps.Count, 1).Value2 = Application.Transpose(apps.Items)

    Set apps = Nothing
End Sub

'Similar to: http://msdn.microsoft.com/en-us/library/aa393618%28VS.85%29.aspx
Public Function AllRunningApps() As Dictionary
    Dim strComputer As String
    Dim objServices As Object, objProcessSet As Object, Process As Object
    Dim oDic As Object, oDic2 As Object, a() As Variant

    Set oDic = CreateObject("Scripting.Dictionary")

    strComputer = "."

    Set objServices = GetObject("winmgmts:\\" _
        & strComputer & "\root\CIMV2")
    Set objProcessSet = objServices.ExecQuery _
        ("Select Name, ProcessID FROM Win32_Process", , 48)

    For Each Process In objProcessSet
       If Not oDic.exists(Process.Name) Then
        oDic.Add Key:=Process.Properties_("Name").Value, Item:=Process.Properties_("ProcessID").Value
       End If
    Next

    Set AllRunningApps = oDic

    Set objProcessSet = Nothing
    Set oDic = Nothing
End Function

언급URL : https://stackoverflow.com/questions/4038021/vba-return-dictionary-from-function

반응형