Live-Forum - Die aktuellen Beiträge
Anzeige
Archiv - Navigation
1436to1440
Aktuelles Verzeichnis
Verzeichnis Index
Übersicht Verzeichnisse
Vorheriger Thread
Rückwärts Blättern
Nächster Thread
Vorwärts blättern
Anzeige
HERBERS
Excel-Forum (Archiv)
20+ Jahre Excel-Kompetenz: Von Anwendern, für Anwender
Inhaltsverzeichnis

Erweiterung Import

Erweiterung Import
16.07.2015 21:35:08
Bernd
Hallo zusammen,
folgendes Makro, das mir vorliegt (Danke Sepp!) importiert einen vorgegebenen Zellbereich eine vorgegebenen Tabellenblatts aus mehreren Exceldateien. Die zu importierenden Tabellenblätter und Zellbereiche sind identisch. Lässt sich das Makro insofern flexibilisieren, dass ich auch
mehrere Tabellenblätter mit unterschiedlichen Zellbereichen aus auszuwählenden Importdateien einlesen kann? Die Struktur der einzulesenden Importdateien ist einheitlich (Tabellenblätter identisch).
Es wäre schön, wen mir da jemand helfen kann. Vielleicht sogar Sepp, dem ich den tollen Erstcode zu verdanken habe.
Gruß,
Bernd
Option Explicit
Private Const cstrSheetName As String = "Test" 'Name des zu importierenden Tabellenblattes!
Private Const cstrRef As String = "A1:AM6000" 'Importbereich
Sub import()
Dim objADO As Object
Dim vntItem As Variant
Dim vntFiles() As String, strTable As String, strFile As String, strPath As String
Dim lngI As Long, lngN As Long, lngNext As Long, lngCalc As Long
On Error GoTo ErrExit
With Application
.ScreenUpdating = False
.EnableEvents = False
lngCalc = .Calculation
.Calculation = -4135
.DisplayAlerts = False
End With
With Application.FileDialog(msoFileDialogFilePicker)
.InitialFileName = "D:\Schriftverkehr\Herber" 'Startverzeichnis
.Title = "Dateien zum Import auswählen"
.ButtonName = "Import Starten"
.InitialView = msoFileDialogViewList
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Excel Dateien", "*.xls; *.xlsx; *.xlsm", 1
.Filters.Add "Alle Dateien", "*.*", 2
.FilterIndex = 1
If .Show = -1 Then
ReDim vntFiles(.SelectedItems.Count - 1)
For Each vntItem In .SelectedItems
vntFiles(lngI) = vntItem
lngI = lngI + 1
Next
End If
End With
If lngI > 0 Then
With ThisWorkbook.Sheets("Tabelle1") 'Name der Tabelle in dieser Datei - anpassen!
.Range("A1:AN" & .Rows.Count) = ""
lngNext = 2
For lngI = 0 To UBound(vntFiles)
DoEvents
strPath = Mid(vntFiles(lngI), 1, InStrRev(vntFiles(lngI), "\") - 1)
strFile = Mid(vntFiles(lngI), InStrRev(vntFiles(lngI), "\") + 1)
Application.StatusBar = "Import aus '" & strPath & "' - Datei: '" & strFile & _
"' - ( " & lngI + 1 & " von " & UBound(vntFiles) + 1 & " )"
DoEvents
strTable = cstrSheetName
Set objADO = ExcelTable(vntFiles(lngI), strTable, cstrRef)
If lngI = 0 Then
For lngN = 1 To objADO.Fields.Count
.Cells(1, lngN) = objADO.Fields.Item(lngN - 1).Name
Next
.Cells(1, lngN) = "Aus Datei"
End If
.Cells(lngNext, 1).CopyFromRecordset objADO
.Cells(lngNext, lngN).Resize(objADO.RecordCount, 1) = vntFiles(lngI)
.Cells(lngNext, lngN).Hyperlinks.Add anchor:=.Cells(lngNext, lngN), Address:=vntFiles(lngI), SubAddress:=""
lngNext = lngNext + objADO.RecordCount
objADO.Close
Next
.Columns.AutoFit
End With
MsgBox "Import aus " & IIf(UBound(vntFiles) = 0, "einer Datei", UBound(vntFiles) + 1 & " Dateien") & _
" erfolgreich abgeschloßen!", vbInformation
End If
ErrExit:
With Err
If .Number 0 Then
MsgBox "Fehler in Prozedur:" & vbTab & "'import'" & vbLf & String(60, "_") & _
vbLf & vbLf & IIf(Erl, "Fehler in Zeile:" & vbTab & Erl & vbLf & vbLf, "") & _
"Fehlernummer:" & vbTab & .Number & vbLf & vbLf & "Beschreibung:" & vbTab & _
.Description & vbLf, vbExclamation + vbMsgBoxSetForeground, _
"VBA - Fehler in Prozedur - import"
.Clear
End If
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = lngCalc
.DisplayAlerts = True
.StatusBar = False
End With
On Error GoTo 0
Set objADO = Nothing
End Sub
Private Function ExcelTable(ByRef Path As String, ByRef Table As String, ByRef SourceRange As   _
_
String, Optional WhereString As String = "") As Object
' requires the function FileExists()
Dim SQL As String
Dim Con As String
If Not FileExists(Path) Then Exit Function
SQL = "select * from [" & Table & "$" & SourceRange & "] " & WhereString
If Mid(Path, InStrRev(Path, ".") + 1) = "xls" Then
Con = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Extended Properties=Excel 8.0;" _
& "Data Source=" & Path & ";"
ElseIf Mid(Path, InStrRev(Path, ".") + 1) Like "xls?" Then
Con = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Extended Properties=""Excel 12.0;HDR=YES"";" _
& "Data Source=" & Path & ";"
Else
Exit Function
End If
Set ExcelTable = CreateObject("ADODB.Recordset")
ExcelTable.Open SQL, Con, 3, 1
End Function
Private Function FileExists(FileName As String) As Boolean
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileExists = objFSO.FileExists(FileName)
Set objFSO = Nothing
End Function

10
Beiträge zum Forumthread
Beiträge zu diesem Forumthread

Betreff
Datum
Anwender
Anzeige
AW: Erweiterung Import
16.07.2015 21:46:53
Sepp
Hallo Bernd,
alle Importe in das selbe Tabellenblatt?
Gruß Sepp

AW: Erweiterung Import
16.07.2015 21:52:18
Bernd
Hallo Sepp,
zuerst mal vielen Dank für den tollen Code. Ich wollte Dir noch danken, aber man hat wohl nur noch wenige Tage Zeit, dann geht nichts mehr! Ich bin übrigens zunächst auf dem Schlauch gestanden, das Makro öffnet die Dateien durch Mehrfachmarkierung. Das war mir so nicht klar, deswegen hat es den Import also dauernd "überschrieben".
Jetzt zur Erweiterung:
Die Daten sollten jeweils in ein eigenes Tabellenblatt in der Zieldatei "reinlaufen".
Viele Grüße
Bernd

Anzeige
Noch eine Frage
16.07.2015 22:08:24
Sepp
Hallo bernd,
immer in die selben Tabellenblätter in der Zieldatei, oder sollen für jeden Import neue Blätter angelegt werden?
Gruß Sepp

AW: Erweiterung Import
16.07.2015 23:06:08
Sepp
Hallo Bernd,
mal zum Testen mit fixen Zieltabellen.
' **********************************************************************
' Modul: Modul1 Typ: Allgemeines Modul
' **********************************************************************

Option Explicit

Sub import()
  Dim objADO As Object
  Dim vntItem As Variant
  Dim vntFiles() As String, strTable As String, strFile As String, strPath As String
  Dim lngI As Long, lngN As Long, lngR As Long, lngNext() As Long, lngCalc As Long
  Dim vntRef(2) As String
  
  On Error GoTo ErrExit
  
  With Application
    .ScreenUpdating = False
    .EnableEvents = False
    lngCalc = .Calculation
    .Calculation = -4135
    .DisplayAlerts = False
  End With
  
  '### !!! ###
  'Array für Tabellenname(n) und Bereich(e) - ZielTabelle$QuellTabelle$Importbereich
  vntRef(0) = "Tabelle1$Test$A1:AM600"
  vntRef(1) = "Tabelle2$Tabelle2$A1:U5000"
  vntRef(2) = "Tabelle3$Import$A1:G5000"
  
  Redim lngNext(UBound(vntRef))
  
  With Application.FileDialog(msoFileDialogFilePicker)
    .InitialFileName = "D:\Schriftverkehr\Herber" 'Startverzeichnis
    .Title = "Dateien zum Import auswählen"
    .ButtonName = "Import Starten"
    .InitialView = msoFileDialogViewList
    .AllowMultiSelect = True
    .Filters.Clear
    .Filters.Add "Excel Dateien", "*.xls; *.xlsx; *.xlsm", 1
    .Filters.Add "Alle Dateien", "*.*", 2
    .FilterIndex = 1
    If .Show = -1 Then
      Redim vntFiles(.SelectedItems.Count - 1)
      For Each vntItem In .SelectedItems
        vntFiles(lngI) = vntItem
        lngI = lngI + 1
      Next
    End If
  End With
  
  If lngI > 0 Then
    For lngI = 0 To UBound(vntFiles)
      For lngR = 0 To UBound(vntRef)
        With ThisWorkbook.Sheets(Split(vntRef(lngR), "$")(0))
          If lngNext(lngR) = 0 Then
            .UsedRange = ""
            lngNext(lngR) = 2
          End If
          strPath = Mid(vntFiles(lngI), 1, InStrRev(vntFiles(lngI), "\") - 1)
          strFile = Mid(vntFiles(lngI), InStrRev(vntFiles(lngI), "\") + 1)
          DoEvents
          Application.StatusBar = "Import aus '" & strPath & "' - Datei: '" & strFile & "' - ( " & _
            lngI + 1 & " von " & UBound(vntFiles) + 1 & " )" & " Aus Tabelle: '" & Split(vntRef(lngR), _
            "$")(1) & "' - ( " & lngR + 1 & " von " & UBound(vntRef) + 1 & " )"
          DoEvents
          Set objADO = ExcelTable(vntFiles(lngI), CStr(Split(vntRef(lngR), "$")(1)), _
            CStr(Split(vntRef(lngR), "$")(2)))
          If lngI = 0 Then
            For lngN = 1 To objADO.Fields.Count
              .Cells(1, lngN) = objADO.Fields.Item(lngN - 1).Name
            Next
            .Cells(1, lngN) = "Aus Datei"
          Else
            lngN = objADO.Fields.Count + 1
          End If
          .Cells(lngNext(lngR), 1).CopyFromRecordset objADO
          .Cells(lngNext(lngR), lngN).Resize(objADO.RecordCount, 1) = vntFiles(lngI)
          .Cells(lngNext(lngR), lngN).Hyperlinks.Add anchor:=.Cells(lngNext(lngR), lngN), _
            Address:=vntFiles(lngI), SubAddress:=""
          lngNext(lngR) = lngNext(lngR) + objADO.RecordCount
          objADO.Close
          Set objADO = Nothing
          .Columns.AutoFit
        End With
      Next
    Next
    
    MsgBox "Import aus " & IIf(UBound(vntFiles) = 0, "einer Datei", _
      UBound(vntFiles) + 1 & " Dateien") & " und jeweils " & UBound(vntRef) + 1 & _
      " Tabellen erfolgreich abgeschloßen!", vbInformation
  End If
  
  ErrExit:
  
  With Err
    If .Number <> 0 Then
      MsgBox "Fehler in Prozedur:" & vbTab & "'import'" & vbLf & String(60, "_") & vbLf & vbLf & _
        IIf(Erl, "Fehler in Zeile:" & vbTab & Erl & vbLf & vbLf, "") & "Fehlernummer:" & vbTab & _
        .Number & vbLf & vbLf & "Beschreibung:" & vbTab & .Description & vbLf, vbExclamation + _
        vbMsgBoxSetForeground, "VBA - Fehler in Prozedur - import"
      .Clear
    End If
  End With
  
  With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = lngCalc
    .DisplayAlerts = True
    .StatusBar = False
  End With
  
  On Error GoTo 0
  
  Set objADO = Nothing
End Sub


Private Function ExcelTable(ByRef Path As String, ByRef Table As String, ByRef SourceRange As String, Optional WhereString As String = "") As Object
  ' requires the function FileExists()
  Dim SQL As String
  Dim Con As String
  
  If Not FileExists(Path) Then Exit Function
  
  SQL = "select * from [" & Table & "$" & SourceRange & "] " & WhereString
  
  If Mid(Path, InStrRev(Path, ".") + 1) = "xls" Then
    Con = "Provider=Microsoft.Jet.OLEDB.4.0;" _
      & "Extended Properties=Excel 8.0;" _
      & "Data Source=" & Path & ";"
  ElseIf Mid(Path, InStrRev(Path, ".") + 1) Like "xls?" Then
    Con = "Provider=Microsoft.ACE.OLEDB.12.0;" _
      & "Extended Properties=""Excel 12.0;HDR=YES"";" _
      & "Data Source=" & Path & ";"
  Else
    Exit Function
  End If
  Set ExcelTable = CreateObject("ADODB.Recordset")
  ExcelTable.Open SQL, Con, 3, 1
End Function


Private Function FileExists(FileName As String) As Boolean
  Dim objFSO As Object
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  FileExists = objFSO.FileExists(FileName)
  Set objFSO = Nothing
End Function


Gruß Sepp

Anzeige
AW: Erweiterung Import
17.07.2015 09:46:46
Bernd
Hallo Sepp,
läuft gut! Ist die andere Variante noch möglich oder zu viel Anpassungen?
Viele Grüße
Bernd

AW: Erweiterung Import
17.07.2015 18:49:47
Sepp
Hallo Bernd,
fast alles ist möglich! Wie soll es den ablaufen? Du weißt was du willst, ich kann nur raten!
Gruß Sepp

AW: Erweiterung Import
17.07.2015 19:57:08
Sepp
Hallo Bernd,
so mit neuen Tabellen je Import.
' **********************************************************************
' Modul: Modul1 Typ: Allgemeines Modul
' **********************************************************************

Option Explicit

Sub import()
  Dim objADO As Object
  Dim vntItem As Variant
  Dim vntFiles() As String, strFile As String, strPath As String
  Dim lngI As Long, lngN As Long, lngR As Long, lngNext() As Long, lngCalc As Long
  Dim vntRef(2) As String, vntSheet() As Object
  
  On Error GoTo ErrExit
  
  With Application
    .ScreenUpdating = False
    .EnableEvents = False
    lngCalc = .Calculation
    .Calculation = -4135
    .DisplayAlerts = False
  End With
  
  '### !!! ###
  'Array für Tabellenname(n) und Bereich(e) - QuellTabelle$Importbereich
  vntRef(0) = "Test$A1:AM600"
  vntRef(1) = "Tabelle2$A1:U5000"
  vntRef(2) = "Import$A1:G5000"
  
  Redim lngNext(UBound(vntRef))
  Redim vntSheet(UBound(vntRef))
  
  With Application.FileDialog(msoFileDialogFilePicker)
    .InitialFileName = "D:\Schriftverkehr\Herber" 'Startverzeichnis
    .Title = "Dateien zum Import auswählen"
    .ButtonName = "Import Starten"
    .InitialView = msoFileDialogViewList
    .AllowMultiSelect = True
    .Filters.Clear
    .Filters.Add "Excel Dateien", "*.xls; *.xlsx; *.xlsm", 1
    .Filters.Add "Alle Dateien", "*.*", 2
    .FilterIndex = 1
    If .Show = -1 Then
      Redim vntFiles(.SelectedItems.Count - 1)
      For Each vntItem In .SelectedItems
        vntFiles(lngI) = vntItem
        lngI = lngI + 1
      Next
    End If
  End With
  
  For lngI = 0 To UBound(vntRef)
    With ThisWorkbook
      Set vntSheet(lngI) = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
      vntSheet(lngI).Name = Left(Format(Now, "ddmmyy_hhmmss") & "-" & Split(vntRef(lngI), "$")(0), 31)
    End With
  Next
  
  If lngI > 0 Then
    For lngI = 0 To UBound(vntFiles)
      For lngR = 0 To UBound(vntRef)
        With vntSheet(lngR)
          If lngNext(lngR) = 0 Then
            .UsedRange = ""
            lngNext(lngR) = 2
          End If
          strPath = Mid(vntFiles(lngI), 1, InStrRev(vntFiles(lngI), "\") - 1)
          strFile = Mid(vntFiles(lngI), InStrRev(vntFiles(lngI), "\") + 1)
          DoEvents
          Application.StatusBar = "Import aus '" & strPath & "' - Datei: '" & strFile & "' - ( " & _
            lngI + 1 & " von " & UBound(vntFiles) + 1 & " )" & " Aus Tabelle: '" & Split(vntRef(lngR), _
            "$")(1) & "' - ( " & lngR + 1 & " von " & UBound(vntRef) + 1 & " )"
          DoEvents
          Set objADO = ExcelTable(vntFiles(lngI), CStr(Split(vntRef(lngR), "$")(0)), _
            CStr(Split(vntRef(lngR), "$")(1)))
          If lngI = 0 Then
            For lngN = 1 To objADO.Fields.Count
              .Cells(1, lngN) = objADO.Fields.Item(lngN - 1).Name
            Next
            .Cells(1, lngN) = "Aus Datei"
          Else
            lngN = objADO.Fields.Count + 1
          End If
          .Cells(lngNext(lngR), 1).CopyFromRecordset objADO
          .Cells(lngNext(lngR), lngN).Resize(objADO.RecordCount, 1) = vntFiles(lngI)
          .Cells(lngNext(lngR), lngN).Hyperlinks.Add anchor:=.Cells(lngNext(lngR), lngN), _
            Address:=vntFiles(lngI), SubAddress:=""
          lngNext(lngR) = lngNext(lngR) + objADO.RecordCount
          objADO.Close
          Set objADO = Nothing
          .Columns.AutoFit
        End With
      Next
    Next
    
    MsgBox "Import aus " & IIf(UBound(vntFiles) = 0, "einer Datei", _
      UBound(vntFiles) + 1 & " Dateien") & " und jeweils " & UBound(vntRef) + 1 & _
      " Tabellen erfolgreich abgeschloßen!", vbInformation
  End If
  
  ErrExit:
  
  With Err
    If .Number <> 0 Then
      MsgBox "Fehler in Prozedur:" & vbTab & "'import'" & vbLf & String(60, "_") & vbLf & vbLf & _
        IIf(Erl, "Fehler in Zeile:" & vbTab & Erl & vbLf & vbLf, "") & "Fehlernummer:" & vbTab & _
        .Number & vbLf & vbLf & "Beschreibung:" & vbTab & .Description & vbLf, vbExclamation + _
        vbMsgBoxSetForeground, "VBA - Fehler in Prozedur - import"
      .Clear
    End If
  End With
  
  With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = lngCalc
    .DisplayAlerts = True
    .StatusBar = False
  End With
  
  On Error GoTo 0
  
  Set objADO = Nothing
End Sub



Private Function ExcelTable(ByRef Path As String, ByRef Table As String, ByRef SourceRange As String, Optional WhereString As String = "") As Object
  ' requires the function FileExists()
  Dim SQL As String
  Dim Con As String
  
  If Not FileExists(Path) Then Exit Function
  
  SQL = "select * from [" & Table & "$" & SourceRange & "] " & WhereString
  
  If Mid(Path, InStrRev(Path, ".") + 1) = "xls" Then
    Con = "Provider=Microsoft.Jet.OLEDB.4.0;" _
      & "Extended Properties=Excel 8.0;" _
      & "Data Source=" & Path & ";"
  ElseIf Mid(Path, InStrRev(Path, ".") + 1) Like "xls?" Then
    Con = "Provider=Microsoft.ACE.OLEDB.12.0;" _
      & "Extended Properties=""Excel 12.0;HDR=YES"";" _
      & "Data Source=" & Path & ";"
  Else
    Exit Function
  End If
  Set ExcelTable = CreateObject("ADODB.Recordset")
  ExcelTable.Open SQL, Con, 3, 1
End Function



Private Function FileExists(FileName As String) As Boolean
  Dim objFSO As Object
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  FileExists = objFSO.FileExists(FileName)
  Set objFSO = Nothing
End Function


Gruß Sepp

Anzeige
kleine Korrektur
18.07.2015 08:09:18
Sepp
Hallo Bernd,
ich hatte noch einen kleine Fehler im Code, nimm diesen.
' **********************************************************************
' Modul: Modul1 Typ: Allgemeines Modul
' **********************************************************************

Option Explicit

Sub import()
  Dim objADO As Object
  Dim vntItem As Variant
  Dim vntFiles() As String, strFile As String, strPath As String
  Dim lngI As Long, lngN As Long, lngR As Long, lngNext() As Long, lngCalc As Long
  Dim vntRef(2) As String, vntSheet() As Object
  
  On Error GoTo ErrExit
  
  With Application
    .ScreenUpdating = False
    .EnableEvents = False
    lngCalc = .Calculation
    .Calculation = -4135
    .DisplayAlerts = False
  End With
  
  '### !!! ###
  'Array für Tabellenname(n) und Bereich(e) - QuellTabelle$Importbereich
  vntRef(0) = "Test$A1:AM600"
  vntRef(1) = "Tabelle2$A1:U5000"
  vntRef(2) = "Import$A1:G5000"
  
  Redim lngNext(UBound(vntRef))
  Redim vntSheet(UBound(vntRef))
  
  With Application.FileDialog(msoFileDialogFilePicker)
    .InitialFileName = "D:\Schriftverkehr\Herber" 'Startverzeichnis
    .Title = "Dateien zum Import auswählen"
    .ButtonName = "Import Starten"
    .InitialView = msoFileDialogViewList
    .AllowMultiSelect = True
    .Filters.Clear
    .Filters.Add "Excel Dateien", "*.xls; *.xlsx; *.xlsm", 1
    .Filters.Add "Alle Dateien", "*.*", 2
    .FilterIndex = 1
    If .Show = -1 Then
      Redim vntFiles(.SelectedItems.Count - 1)
      For Each vntItem In .SelectedItems
        vntFiles(lngI) = vntItem
        lngI = lngI + 1
      Next
    End If
  End With
  
  If lngI > 0 Then
    For lngR = 0 To UBound(vntRef)
      With ThisWorkbook
        Set vntSheet(lngR) = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
        vntSheet(lngR).Name = Left(Format(Now, "ddmmyy_hhmmss") & "-" & Split(vntRef(lngR), "$")(0), 31)
      End With
    Next
    For lngI = 0 To UBound(vntFiles)
      For lngR = 0 To UBound(vntRef)
        With vntSheet(lngR)
          If lngNext(lngR) = 0 Then
            .UsedRange = ""
            lngNext(lngR) = 2
          End If
          strPath = Mid(vntFiles(lngI), 1, InStrRev(vntFiles(lngI), "\") - 1)
          strFile = Mid(vntFiles(lngI), InStrRev(vntFiles(lngI), "\") + 1)
          DoEvents
          Application.StatusBar = "Import aus '" & strPath & "' - Datei: '" & strFile & "' - ( " & _
            lngI + 1 & " von " & UBound(vntFiles) + 1 & " )" & " Aus Tabelle: '" & Split(vntRef(lngR), _
            "$")(1) & "' - ( " & lngR + 1 & " von " & UBound(vntRef) + 1 & " )"
          DoEvents
          Set objADO = ExcelTable(vntFiles(lngI), CStr(Split(vntRef(lngR), "$")(0)), _
            CStr(Split(vntRef(lngR), "$")(1)))
          If lngI = 0 Then
            For lngN = 1 To objADO.Fields.Count
              .Cells(1, lngN) = objADO.Fields.Item(lngN - 1).Name
            Next
            .Cells(1, lngN) = "Aus Datei"
          Else
            lngN = objADO.Fields.Count + 1
          End If
          .Cells(lngNext(lngR), 1).CopyFromRecordset objADO
          .Cells(lngNext(lngR), lngN).Resize(objADO.RecordCount, 1) = vntFiles(lngI)
          .Cells(lngNext(lngR), lngN).Hyperlinks.Add anchor:=.Cells(lngNext(lngR), lngN), _
            Address:=vntFiles(lngI) & "#" & Split(vntRef(lngR), "$")(0) & "!A1", SubAddress:=""
          lngNext(lngR) = lngNext(lngR) + objADO.RecordCount
          objADO.Close
          Set objADO = Nothing
          .Columns.AutoFit
        End With
      Next
    Next
    
    MsgBox "Import aus " & IIf(UBound(vntFiles) = 0, "einer Datei", _
      UBound(vntFiles) + 1 & " Dateien") & " und jeweils " & UBound(vntRef) + 1 & _
      " Tabellen erfolgreich abgeschloßen!", vbInformation
  End If
  
  ErrExit:
  
  With Err
    If .Number <> 0 Then
      MsgBox "Fehler in Prozedur:" & vbTab & "'import'" & vbLf & String(60, "_") & vbLf & vbLf & _
        IIf(Erl, "Fehler in Zeile:" & vbTab & Erl & vbLf & vbLf, "") & "Fehlernummer:" & vbTab & _
        .Number & vbLf & vbLf & "Beschreibung:" & vbTab & .Description & vbLf, vbExclamation + _
        vbMsgBoxSetForeground, "VBA - Fehler in Prozedur - import"
      .Clear
    End If
  End With
  
  With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = lngCalc
    .DisplayAlerts = True
    .StatusBar = False
  End With
  
  On Error GoTo 0
  
  Set objADO = Nothing
End Sub




Private Function ExcelTable(ByRef Path As String, ByRef Table As String, ByRef SourceRange As String, Optional WhereString As String = "") As Object
  ' requires the function FileExists()
  Dim SQL As String
  Dim Con As String
  
  If Not FileExists(Path) Then Exit Function
  
  SQL = "select * from [" & Table & "$" & SourceRange & "] " & WhereString
  
  If Mid(Path, InStrRev(Path, ".") + 1) = "xls" Then
    Con = "Provider=Microsoft.Jet.OLEDB.4.0;" _
      & "Extended Properties=Excel 8.0;" _
      & "Data Source=" & Path & ";"
  ElseIf Mid(Path, InStrRev(Path, ".") + 1) Like "xls?" Then
    Con = "Provider=Microsoft.ACE.OLEDB.12.0;" _
      & "Extended Properties=""Excel 12.0;HDR=YES"";" _
      & "Data Source=" & Path & ";"
  Else
    Exit Function
  End If
  Set ExcelTable = CreateObject("ADODB.Recordset")
  ExcelTable.Open SQL, Con, 3, 1
End Function




Private Function FileExists(FileName As String) As Boolean
  Dim objFSO As Object
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  FileExists = objFSO.FileExists(FileName)
  Set objFSO = Nothing
End Function


Gruß Sepp

Anzeige
Import ADO- finale Version
19.07.2015 16:09:00
Sepp
Hallo Bernd,
hier eine überarbeitete Version mit ein paar Änderungen.
' **********************************************************************
' Modul: Modul1 Typ: Allgemeines Modul
' **********************************************************************

Option Explicit

Sub ImportADO_MultibleFilesAndTables()
  'by j.ehrensberger 07/2015
  Dim objADO As Object, objSheet() As Object
  Dim vntItem As Variant, vntSheets As Variant
  Dim vntFiles() As String, vntRef() As String, strFile As String, strPath As String, strName As String
  Dim lngI As Long, lngN As Long, lngR As Long, lngNext() As Long, lngCalc As Long
  
  On Error GoTo ErrExit
  
  With Application
    .ScreenUpdating = False
    .EnableEvents = False
    lngCalc = .Calculation
    .Calculation = -4135
    .DisplayAlerts = False
  End With
  
  '### IMPORTPARAMETER ###
  
  Redim vntRef(2, 1) '(x = ANZAHL DER TABELLEN - 1, 1)
  
  ' 1. Tabelle
  vntRef(0, 0) = "Test" 'PARAMTER 1 - (x, 0) = TABELLENNAME
  vntRef(0, 1) = "A1:AM600" 'PARAMTER 2 - (x, 1) = BEREICHSADRESSE
  ' 2. Tabelle
  vntRef(1, 0) = "Tabelle2"
  vntRef(1, 1) = "A1:U5000"
  ' 3. Tabelle
  vntRef(2, 0) = "Import"
  vntRef(2, 1) = "A1:G5000"
  
  '### ENDE IMPORTPARAMETER ###
  
  Redim lngNext(UBound(vntRef))
  Redim objSheet(UBound(vntRef))
  
  'Dateiauswahl (Mehrfachauswahl möglich!)
  With Application.FileDialog(msoFileDialogFilePicker)
    .InitialFileName = "E:\Forum" 'Startverzeichnis
    .Title = "Dateien zum Import auswählen"
    .ButtonName = "Import Starten"
    .InitialView = msoFileDialogViewList
    .AllowMultiSelect = True
    .Filters.Clear
    .Filters.Add "Excel Dateien", "*.xls; *.xlsx; *.xlsm", 1
    .Filters.Add "Alle Dateien", "*.*", 2
    .FilterIndex = 1
    If .Show = -1 Then
      Redim vntFiles(.SelectedItems.Count - 1)
      For Each vntItem In .SelectedItems
        vntFiles(lngI) = vntItem
        lngI = lngI + 1
      Next
    End If
  End With
  
  If lngI > 0 Then
    'Datum/Zeit-Zusatz Blattname(n)
    strName = Format(Now, "yyMMdd hhmmss-")
    'Neue Tabellen erstellen und benennen
    For lngR = 0 To UBound(vntRef)
      With ThisWorkbook
        Set objSheet(lngR) = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
        objSheet(lngR).Name = Left(strName & vntRef(lngR, 0), 31)
        objSheet(lngR).Rows(1).Font.Bold = True
      End With
      lngNext(lngR) = 2
    Next
    'Dateien durchlaufen
    For lngI = 0 To UBound(vntFiles)
      'Tabellennamen der aktuellen Importdatei ermitteln
      vntSheets = GetSheetNames(vntFiles(lngI))
      'Import aus den Tabellen
      For lngR = 0 To UBound(vntRef)
        With objSheet(lngR)
          'Strings für Ausgabe in Statuszeile erstellen
          strPath = Mid(vntFiles(lngI), 1, InStrRev(vntFiles(lngI), "\"))
          strFile = Mid(vntFiles(lngI), Len(strPath) + 1)
          'Prüfung ob Tabelle in Importdatei vorhanden
          If IsNumeric(Application.Match(vntRef(lngR, 0), vntSheets, 0)) Then
            'Statuszeilentext
            DoEvents
            Application.StatusBar = "Import aus '" & strPath & "' - Datei: '" & strFile & "' - ( " & _
              lngI + 1 & " von " & UBound(vntFiles) + 1 & " )" & " Aus Tabelle: '" & vntRef(lngR, 0) _
              & "' - ( " & lngR + 1 & " von " & UBound(vntRef) + 1 & " )"
            DoEvents
            'ADO-Objekt erstellen
            Set objADO = ExcelTable(vntFiles(lngI), CStr(vntRef(lngR, 0)), _
              CStr(vntRef(lngR, 1)))
            'Spaltenüberschriften eintragen
            If lngI = 0 Then
              For lngN = 1 To objADO.Fields.Count
                .Cells(1, lngN) = objADO.Fields.Item(lngN - 1).Name
              Next
              .Cells(1, lngN) = "Aus Datei"
            Else
              lngN = objADO.Fields.Count + 1
            End If
            'Wenn Daten vorhanden
            If objADO.RecordCount > 0 Then
              'Daten eintragen
              .Cells(lngNext(lngR), 1).CopyFromRecordset objADO
              'Dateiname eintragen und Hyperlink erstellen
              With .Cells(lngNext(lngR), lngN)
                .Resize(objADO.RecordCount, 1) = vntFiles(lngI)
                .Hyperlinks.Add anchor:=.Cells, _
                  Address:=vntFiles(lngI) & "#" & vntRef(lngR, 0) & "!A1"
              End With
              'Zeile für den nächsten Import festlegen
              lngNext(lngR) = lngNext(lngR) + objADO.RecordCount
            End If
            objADO.Close
            Set objADO = Nothing
            .Columns.AutoFit
          End If
        End With
      Next
    Next
    'Meldung
    MsgBox "Import aus " & IIf(UBound(vntFiles) = 0, "einer Datei", _
      UBound(vntFiles) + 1 & " Dateien") & " und jeweils " & UBound(vntRef) + 1 & _
      " Tabellen erfolgreich abgeschloßen!", vbInformation
  End If
  
  'Fehlerbehandlung
  ErrExit:
  
  With Err
    If .Number <> 0 Then
      MsgBox "Fehler in Prozedur:" & vbTab & "'import'" & vbLf & String(60, "_") & vbLf & vbLf & _
        IIf(Erl, "Fehler in Zeile:" & vbTab & Erl & vbLf & vbLf, "") & "Fehlernummer:" & vbTab & _
        .Number & vbLf & vbLf & "Beschreibung:" & vbTab & .Description & vbLf, vbExclamation + _
        vbMsgBoxSetForeground, "VBA - Fehler in Prozedur - import"
      .Clear
    End If
  End With
  
  With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = lngCalc
    .DisplayAlerts = True
    .StatusBar = False
  End With
  
  On Error GoTo 0
  
  Set objADO = Nothing
End Sub


Private Function ExcelTable(ByRef Path As String, ByRef Table As String, ByRef SourceRange As _
    String, Optional WhereString As String = "") As Object

  Dim SQL As String
  Dim Con As String
  
  SQL = "select * from [" & Table & "$" & SourceRange & "] " & WhereString
  
  If Mid(Path, InStrRev(Path, ".") + 1) = "xls" Then
    Con = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Extended Properties=Excel 8.0;" & "Data Source=" & _
      Path & ";"
  ElseIf Mid(Path, InStrRev(Path, ".") + 1) Like "xls?" Then
    Con = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Extended Properties=""Excel 12.0;HDR=YES"";" & _
      "Data Source=" & Path & ";"
  Else
    Exit Function
  End If
  Set ExcelTable = CreateObject("ADODB.Recordset")
  ExcelTable.Open SQL, Con, 3, 1
End Function


Private Function GetSheetNames(ByVal FileName As String) As Variant
  'original by Bob Phillips, adapted by j.ehrensberger
  Dim objADO_Connection As Object, objADO_Catalog As Object, objADO_Tables As Object
  Dim lngIndex As Long, intLength As Integer, intPos As Integer, intStart As Integer
  Dim strConString As String, strTable As String
  Dim vntTmp() As Variant
  
  If Mid(FileName, InStrRev(FileName, ".") + 1) = "xls" Then
    strConString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Extended Properties=Excel 8.0;" & _
      "Data Source=" & FileName & ";"
  ElseIf Mid(FileName, InStrRev(FileName, ".") + 1) Like "xls?" Then
    strConString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Extended Properties=""Excel 12.0;HDR=YES"";" _
      & "Data Source=" & FileName & ";"
  Else
    Exit Function
  End If
  
  Set objADO_Connection = CreateObject("ADODB.Connection")
  objADO_Connection.Open strConString
  Set objADO_Catalog = CreateObject("ADOX.Catalog")
  Set objADO_Catalog.ActiveConnection = objADO_Connection
  
  For Each objADO_Tables In objADO_Catalog.Tables
    strTable = objADO_Tables.Name
    intLength = Len(strTable)
    intPos = 0
    intStart = 1
    'Worksheet name with embedded spaces enclosed by single quotes
    If Left(strTable, 1) = "'" And Right(strTable, 1) = "'" Then
      intPos = 1
      intStart = 2
    End If
    'Worksheet names always end in the "$" character
    If Mid$(strTable, intLength - intPos, 1) = "$" Then
      Redim Preserve vntTmp(lngIndex)
      vntTmp(lngIndex) = Mid$(strTable, intStart, intLength - (intStart + intPos))
      lngIndex = lngIndex + 1
    End If
  Next objADO_Tables
  
  If lngIndex > 0 Then GetSheetNames = vntTmp
  
  objADO_Connection.Close
  Set objADO_Catalog = Nothing
  Set objADO_Connection = Nothing
End Function


Gruß Sepp

Anzeige
Perfekt! Vielen Dank!
20.07.2015 09:01:42
Bernd
Hallo Sepp,
vielen Dank nochmal! Ich muss die verschiedenen Version jetzt erst mal ausgiebig testen übewr einen längeren Zeitraum. Vielleicht fällt mir dann noch was ein, was man noch ändern könnte...
Ich poste dann den Code einfach nochmal!
Viele Grüße
Bernd

Beliebteste Forumthreads (12 Monate)

Anzeige

Beliebteste Forumthreads (12 Monate)

Anzeige
Anzeige
Anzeige