Domi.T. hat geschrieben: ↑Di 15. Apr 2025, 07:39
Hallo zusammen,
vielleicht kann mir jemand weiterhelfen.
Ich will CSV Dateien die im gleichen Ordner gespeichert sind wie die Calc-Datei beim öffnen der Calc Datei automatisch einladen.
Der Ordnerpfad und die Namen der CSV Dateien müssen Variabel sein, da es je Projekt eine solche Hauptdatei geben soll.
Die CSV Daten sollen dann aufeinanderfolgend in das Tabellenblatt eingeladen werden.
Leider kenne ich mich mit der Makrothematik nicht gut aus, oder vielleicht gibt es einen anderen Weg?
Kann mir da jemand helfen?
Habe es selbst gelöst - bzw. KI hat es gelöst..
Sub ImportAllCSVsFromDocumentFolder()
Dim oDoc As Object, oSheet As Object
Dim FolderPath As String
Dim FileName As String, FilePath As String
Dim InputStream As Object
Dim line As String, rowData() As String
Dim i As Integer, j As Integer
Dim firstLine As Boolean
Dim startRow As Integer, lastRow As Integer
'

Aktuelles Dokument und Arbeitsblatt holen
oDoc = ThisComponent
oSheet = oDoc.Sheets(0)
startRow = 6
lastRow = startRow
'

Speicherpfad der aktuellen Datei holen
FolderPath = GetCurrentDocumentPath()
If FolderPath = "" Then
MsgBox "Datei muss zuerst gespeichert werden!", 16, "Fehlender Pfad"
Exit Sub
End If
'

CSV-Dateien im Ordner finden
FileName = Dir(FolderPath & "*.csv")
If FileName = "" Then
MsgBox "Keine CSV-Dateien im Ordner gefunden!", 48, "Abbruch"
Exit Sub
End If
'

Durch alle CSV-Dateien iterieren
Do While FileName <> ""
FilePath = FolderPath & FileName
Set InputStream = CreateObject("Scripting.FileSystemObject").OpenTextFile(FilePath, 1, False, 0)
firstLine = True
Do Until InputStream.AtEndOfStream
line = InputStream.ReadLine
If firstLine Then
firstLine = False
If Left(line, 3) = Chr(239) & Chr(187) & Chr(191) Then
line = Mid(line, 4)
End If
End If
If Trim(line) <> "" Then
rowData = Split(line, ";")
For j = 0 To UBound(rowData)
oSheet.getCellByPosition(j, lastRow).String = rowData(j)
Next j
lastRow = lastRow + 1
End If
Loop
InputStream.Close
MsgBox "Importiert: " & FileName, 64, "CSV Import"
FileName = Dir() ' ➡ nächste Datei holen
Loop
MsgBox "Alle CSV-Dateien erfolgreich importiert!", 64, "Fertig"
End Sub
Function GetCurrentDocumentPath() As String
Dim oDoc As Object, sURL As String, sPath As String
Dim lastSlashPos As Integer, i As Integer
oDoc = ThisComponent
sURL = oDoc.getURL()
If sURL = "" Then
GetCurrentDocumentPath = ""
Exit Function
End If
sPath = ConvertFromURL(sURL)
For i = Len(sPath) To 1 Step -1
If Mid(sPath, i, 1) = "\" Or Mid(sPath, i, 1) = "/" Then
lastSlashPos = i
Exit For
End If
Next i
GetCurrentDocumentPath = Left(sPath, lastSlashPos)
End Function