2017-03-12 13 views
1

통합 문서를 사용자에게 묻고 열고 열고 일부 정보를 얻은 다음 닫는 코드를 다음과 같이 사용하고 있습니다. 현재는 통합 문서 모음 및 색인 ("woorkbooks (2)")을 사용하여 열린 통합 문서를 처리합니다. 이제 두 개의 통합 문서를 열어야합니다. 문제는 통합 문서 중 2 개를 인덱스로 지정하고 3을 인덱스로 지정한다는 것입니다. 따라서 각 레코드에 대한 참조를 얻는 방법이 있어야한다고 생각했습니다. 학습장. Excel VBA, FileDialog를 사용하여 여러 통합 문서를 열고 참조하십시오.

Function openfile() As Boolean 

Dim fd As FileDialog 
Dim file_was_chosen As Boolean 

Set fd = Application.FileDialog(msoFileDialogOpen) 

With fd 
    .Filters.Clear 
    .Filters.Add "Excel File", "*.xl*" 
End With 

file_was_chosen = fd.Show 

If Not file_was_chosen Then 
    MsgBox "You didn't select a file" 
    openfile = False 
    Exit Function 
End If 

fd.Execute 
openfile = True 

End Function 

는 지금은 각 통합 문서의 전체 경로를 받고 관련된이 문제에 대한 몇 가지 솔루션을 본 적이 있지만 나는 그것이 다른 언어의 단어 (통합 문서의 이름을 포함하기 때문에 전체 경로를 사용하지 원합니다 물음표와 함께 나타납니다). 또한, 나는 사용자가 두 번이 아니라 두 번만 promp 된 솔루션을 선호합니다.

답변

2

이 버전은 사용자에게 단일 대화 상자를 제공합니다. 즐겨. 그리고 누구든지 내 다른 대답을 downvote, downvote가 필요하다고 그것에 대해 너무 싫어하는 것을 설명하는 의견을 추가하십시오.

Function openfile() As Variant 
    Dim aOpen(2) As String, itm As Variant, cnt As Long, lAsk As Long 
    Dim fd As FileDialog 
    Dim file_was_chosen As Boolean 

    Set fd = Application.FileDialog(msoFileDialogOpen) 

    With fd 
     .Filters.Clear 
     .Filters.Add "Excel File", "*.xl*" 
    End With 

    Do 
     file_was_chosen = fd.Show 
     If Not file_was_chosen Or fd.SelectedItems.Count > 2 Then 
      lAsk = MsgBox("You didn't select one or two files, try again?", vbQuestion + vbYesNo, "File count mismatch") 
      If lAsk = vbNo Then 
       openfile = aOpen 
       Exit Function 
      End If 
     End If 
    Loop While fd.SelectedItems.Count < 1 Or fd.SelectedItems.Count > 2 

    cnt = 0 
    For Each itm In fd.SelectedItems 
     aOpen(cnt) = itm 
     cnt = cnt + 1 
    Next 
    openfile = aOpen 
    fd.Execute 
End Function 

Sub test() 
    Dim vRslt As Variant 
    Dim wkb As Excel.Workbook, wkb1 As Excel.Workbook, wkb2 As Excel.Workbook 

    vRslt = openfile 
    For Each wkb In Application.Workbooks 
     If wkb.Path & "\" & wkb.Name = vRslt(0) Then Set wkb1 = wkb 
     If wkb.Path & "\" & wkb.Name = vRslt(1) Then Set wkb2 = wkb 
    Next 

    If vRslt(0) = "" Then ' no files 
     MsgBox "No files opened so nothing happens..." 
    ElseIf vRslt(1) = "" Then ' one file was opened 
     MsgBox "One file so do whatever you want for one file" 
    Else ' two files were opened 
     MsgBox "Two files so do whatever you want for two files" 
    End If   
End Sub 
+0

대단히 감사합니다. 정확히 필요한 것입니다. (그리고 내 변수와 일관성있게 대해 주셔서 감사합니다. 매우 유용했습니다) – Sergey

0

기존 openfile 함수를 사용하여 부울에서 Excel.Workbook으로 돌아갑니다. 그들이 통합 문서를 열지 않으면 false 대신 Nothing으로 설정합니다. 그렇지 않으면 방금 연 파일의 통합 문서 참조로 설정합니다 (해당 참조를 얻으려면 openfile을 수정해야합니다). 그런 다음 두 번 호출하고 Nothing이 아닌 각 호출에 대한 통합 문서 참조를 설정합니다.

아래의 예제 코드는 자유 형식으로 작성되었으며 테스트되지 않았습니다. 실제로는 가상화 된 의사 코드이지만 실제로 올바른 방향을 제시해야합니다.

sub test 
    dim lAsk as long 
    dim wkb1 as excel.workbook 
    dim wkb2 as excel.workbook 
    do 
     if wkb1 is Nothing then 
      set wkb1 = openfile 
      if wkb1 is Nothing then 
       lAsk = msgbox("you didn't select a first file, try again?",vbyesno,"No file selected") 
       if lAsk = vbNo then exit do 
      end if 
     elseif wkb2 is Nothing then 
      set wkb2 = openfile 
      if wkb2 is Nothing then 
       lAsk = msgbox("you didn't select a second file, try again?",vbyesno,"No file selected") 
       if lAsk = vbNo then exit do 
      end if 
     end if 
    loop while wkb1 is Nothing or wkb2 is Nothing 

    ' do whatever with wkb1 and wkb2 here 

end sub 

편집은 추가 :

여기에 귀하의 기능 openfile 개정에 대한 아주 기본적인 형태입니다. 다시 말하지만, 아직 테스트되지 않았으므로 작동하도록해야합니다.

Function openfile() As Excel.Workbook 
    Dim sFilter As String 
    Dim sTitle As String 
    Dim vFileName As Variant 

    sFilter = "Excel Files (*.xl*), *.xl*, CSV Files (*.csv), *.csv, All Files (*.*), *.*" 
    sTitle = "Select file to process" 

    vFileName = Application.GetOpenFilename(filefilter:=sFilter, Title:=sTitle) 
    If vFileName = False Then 
     Set openfile = Nothing 
    Else 
     Set openfile = Workbooks.Open(Filename:=vFileName) 
    End If 
End Function