이것은 정말 저를 곤두박질칩니다. 어제 모듈 (see here) 사이에 전달되는 컬렉션에 관한 질문을했지만, 더 이상 설명을 듣지 않는 것처럼 보입니다. 따라서 일반적인 방법으로 문제를보다 명확하게 다시 말하려고 시도하고 있습니다.엑셀 배열과 컬렉션 사이에 전달되는 컬렉션이 값을 엉망으로 만들었습니다.
모듈 (module1)과 사용자 정의 (userform1)가 있습니다. 나는 userform1에 콜렉션 (또는 배열)을 만들고이 배열에 워크 시트 객체를 추가합니다. 그런 다음 addNewFile이라는 userform1의 하위를 호출하는 module1에 컨트롤을 전달합니다. addNewFile은 새로 만든 통합 문서를 컬렉션에 추가해야합니다. 그러나 module1이 addNewFile을 호출 할 때마다 다음과 같은 두 가지 시나리오 중 하나가 발생합니다. 1) 콜렉션이 지워지고 추가 된 모든 워크 시트가 이제 콜렉션에 대해 사라졌습니다. 2) 유형이 일치하지 않는다는 오류가 발생합니다. (배열의 경우). 왜 이런 일이 일어나고 있는지 모르겠으니 아래 코드는 더 잘 설명합니다. 배열에 워크 시트 개체를 저장할 수 없다고 말하는 경우에도 도움이 될 것입니다.
UserForm1을
Dim workBooksCollection as New Collection 'can also define as an array
Private Sub CommandButton1_click()
Dim mainWorkBook as workbook
Set mainWorkBook = ActiveWorkbook
Dim testwb As Workbook
workBooksCollection.Add Item:=mainWorkBook, key:="main" 'Adds successfully
workBooksCollection.Add Item:=testwb, key:="test" 'Adds successfully
MsgBox "the size of the array is: " & usedWorkBooks.Count 'Prints off as size 2
Module1.initialize
'After running initialize, prints off as size 0, meaning collection has been erased
MsgBox "the size of the array is: " & usedWorkBooks.Count 'Prints off as size 0
End Sub
Public Sub addNewFile(filepath As String, sheetKey As String)
Dim newWorkBook As Workbook
Set newWorkBook = Workbooks.Open(filepath)
MsgBox "The name of the workbook is: " & newWorkBook.name 'Prints off name of workbook successfully
workBooksCollection.Add Item:=newWorkBook, key:=sheetKey
MsgBox "the size of the array is: " & workBooksCollection.Count 'Prints off as size 1
End Sub
Module1의
Public Sub intialize()
Dim filepath as string
'The filepath is set to any path of a workbook
'This will print out that the array size is 1
UserForm1.addNewFile filePath, "secondBook"
End Sub
미안 내가 여기 죽은 말을 치는 것 같다,하지만 난 정말 여기에서 무슨 일이 일어나고 있는지 어떤 생각이없는 경우. 나는 컬렉션과리스트가 글로벌이면서 다른 모듈에 의해 참조 될 때 변경되지 않는다는 생각에 익숙하다. 여기서 무슨 일이 일어나고 있는지에 대한 도움은 아주 좋습니다.
또한이 문제는 통합 문서가 아닌 모든 데이터 형식에서 발생합니다. – derigible
당신은'workBooksCollection' 컬렉션 객체를 초기화하지 않는 것 같습니다 ('Set workBooksCollection = New collection'). 그게 어디서 일어난거야? –
죄송합니다. workBooksCollection 앞에 New 연산자를 추가하는 것을 잊었습니다. 이제는'Dim workBooksCollection as New Collection'을 읽습니다. – derigible