2017-09-29 3 views
0

Unten ist mein Code für mehrere Dateien zu öffnen und dann einige Aktionen auf ihnen. Ich erwähne nur den Teil, wo ich Hilfe brauche.Multiselect vba

Sub Sample() 
Dim myFile As Variant 
Dim i As Integer 

myFile = Application.GetOpenFilename(MultiSelect:=True) 

If IsArray(myFile) Then 
    For i = LBound(myFile) To UBound(myFile) 
    Set mywkbook= Workbooks.Open(myFile(i)) 
    Next i 
End If 
End Sub 

Das funktioniert gut. Aber ich möchte "mywkbook" Variable unterschiedliche Wert für verschiedene Arbeitsmappe haben, so dass ich an ihnen arbeiten kann. Bitte helfen

Antwort

0

Ich habe es so etwas funktionieren:

Dim paths(), wbs() As Workbook 
Dim x As Integer 

paths = Application.GetOpenFilename(FileFilter:="Excel Files 
(*.XLSX),*.XLSX", MultiSelect:=True) 


    For x = 1 To UBound(paths) 
    ReDim wbs(UBound(paths)) 
Set wbs(x) = Workbooks.Open(paths(x)) 

    With wbs(x).Sheets("Sheet1") 

    lastrow = .Range("A" & .Rows.Count).End(xlUp).Row 

.Range("A2:X" & lastrow).Copy newexcel.Sheets("RawData").Range("A" & 
newexcel.Sheets("RawData").Rows.Count).End(xlUp).Offset(1) 

End With 
Next x 

Posting meine Antwort so, dass es jemand in Zukunft helfen kann :)

0

Eine skalare Variable kann nicht unterschiedliche Werte zur gleichen Zeit, so dass Sie ein Array verwenden müssen. Sie können dies tun, indem Sie Ihren Code wie folgt ändern:

0

Hoffentlich kommt dies durch, ok, das ist meine erste Antwort auf dieses Forum.

Sub tryThis() 

Dim myFile As Variant 
Dim i As Integer 
Dim workbookNames() As String ' define a empty string array variable to hold the file names 

myFile = Application.GetOpenFilename(MultiSelect:=True) 

If IsArray(myFile) Then 
    For i = LBound(myFile) To UBound(myFile) 
     Workbooks.Open (myFile(i)) ' Just open the workbook here 
     ReDim Preserve workbookNames(i) ' ReDim redefines your array to 'i' number of elements. Preserve ensures you don't lose the previous values held in the Array 
     workbookNames(i) = ActiveWorkbook.Name ' Assign the Name of the Workbook to the Array 
      MsgBox workbookNames(i) ' you don't need this, I just used it to demonstrate that you now have the file name and can work with it 
    Next i 
End If 

End Sub 

Edit: Ich habe dies zur gleichen Zeit wie 'Binarus' gebunden. Ich mag ihren Ansatz, ein Arbeitsmappenarray zu deklarieren, aber Sie müssen die folgende Zeile vor 'Set mywkbooks (i)' hinzufügen, sonst erhalten Sie einen Index außerhalb des Bereichsfehler, da das Array leer ist und noch keine Werte enthalten kann.

ReDim Preserve mywkbooks (i)