2015-05-15 1 views
0

У меня есть 150 текстовых файлов в формате csv с использованием pipe | как разделитель. файлы находятся в разных папках в сети. Имена файлов имеют конкретную дату и имеют суффикс, который содержит дату. Я создал таблицу, которая имеет 3 поля: Местоположение файла; Имя файла, исключая суффикс; суффикс (в формате yymmdd).Импорт 150 текстовых файлов для доступа в виде таблиц с использованием SQL

Я хочу создать SQL-скрипт, который будет импортировать каждый из 150 файлов, названных в таблице, которые я создал в 150 отдельных таблиц Access 2007, названных в качестве имени файла, исключая суффикс. Я пытался сделать это с помощью VBA, но имена файлов содержат полные остановки, а VBA это не понравилось.

Каждый из файлов имеет другую структуру столбцов, но первая строка всегда является заголовком. Я могу использовать только функции, родные для Access 2007, поскольку организация, в которой я работаю, не позволяет сторонним аддонам или приложениям. У меня нет SQL-сервера, доступного для меня.

Я полный новичок, когда дело доходит до Access и изо всех сил пытаюсь достичь чего-либо, приближающегося к этому. Вы можете помочь?

+0

Я изо всех сил старался достичь того, чего хотел в Access, и поэтому перешел на Excel вместо этого. Приведенный ниже код создает каждый текстовый файл как лист в одной книге Excel с главной таблицей, содержащей имя файла/путь и т. Д. В качестве «основного» листа в книге. Он удаляет все листы, отличные от «Мастер», прежде чем воссоздавать их, и если файл не найден, он оставит чистый лист. – Lowtrawler

ответ

0

Я изо всех сил пытался достичь того, чего хотел в Access, и поэтому перешел к Excel вместо этого. Приведенный ниже код создает каждый текстовый файл как лист в одной книге Excel с главной таблицей, содержащей имя файла/путь и т. Д. В качестве «основного» листа в книге. Он удаляет все листы, отличные от «Мастер», прежде чем воссоздавать их, и если файл не найден, он оставит чистый лист.

Sub ImportFiles() 

'This script looks at a Master list of files for import and imports each to their own tab 
'The files are pipe (|) delimited and can be in any addressable location 
'If any files are not found, the import of that file is skipped, leaving a blank worksheet 

'Close the Report File before starting the import 
    Application.DisplayAlerts = False 
    On Error Resume Next 
    Windows("Report.xlsx").Activate 
    Windows("Report.xlsx").Close SaveChanges:=True 
    On Error GoTo 0 
    Application.DisplayAlerts = True 

'Start by looking at the sheet which contains the Master list of files 
    Sheets("Master").Activate 

'declare three arrays of unknown length 
    Dim FileName() As String 
    Dim FilePath() As String 
    Dim FullName() As String 

'initially there are no files 
    Dim NumberFiles As Integer 
    NumberFiles = 0 

'loop over all of the file cells 
'The master file needs to be structured FileName, FilePath and FullName in that order 
'Change C2 to the cell containing the first FileName in the Master List 
    Dim FileCell As Range 
    Dim TopCell As Range 
    Dim FileRange As Range 

    Set TopCell = Range("C2") 
    Set FileRange = Range(TopCell, TopCell.End(xlDown)) 
    For Each FileCell In FileRange 

'we've found another file! 
    NumberFiles = NumberFiles + 1 

'for each file found, extend all arrays 
    ReDim Preserve FileName(NumberFiles - 1) 
    ReDim Preserve FilePath(NumberFiles - 1) 
    ReDim Preserve FullName(NumberFiles - 1) 

'now store the filename, path and fullname of the new file 
    FileName(NumberFiles - 1) = FileCell.Value 
    FilePath(NumberFiles - 1) = FileCell.Offset(0, 1).Value 
    FullName(NumberFiles - 1) = FileCell.Offset(0, 2).Value 

Next FileCell 

'delete any existing sheets except Master and create new blank sheets 
For Each Sheet In Application.Worksheets 
    Application.DisplayAlerts = False 
    If Sheet.Name <> "Master" Then 
    Sheet.Delete 
    End If 
    Next Sheet 
    Sheets("Master").Activate 
    For i = 1 To (NumberFiles) 
    Worksheets.Add(After:=Sheets(Sheets.Count)).Name = "Sheet" & i 
    Next i 
    ThisWorkbook.Sheets("Sheet1").Select 

'Start the process of import 

'create a workbook object for the workbook where the current macro is running 
    Dim ws As Worksheet 

'import each file into its own sheet 
    For i = 0 To (NumberFiles - 1) 

    Set ws = ThisWorkbook.Sheets("Sheet" & i + 1) 'the current sheet 

'Ignore any missing files and carry on processing 
    Application.DisplayAlerts = False 
    On Error Resume Next 

'This imports the delimited files 
    With ws.QueryTables.Add(Connection:="TEXT;" & FullName(i),  Destination:=ws.Range("$A$1")) 
     .Name = "a" & i 
     .FieldNames = True 
     .RowNumbers = False 
     .FillAdjacentFormulas = False 
     .PreserveFormatting = True 
     .RefreshOnFileOpen = False 
     .RefreshStyle = xlInsertDeleteCells 
     .SavePassword = False 
     .SaveData = True 
     .AdjustColumnWidth = True 
     .RefreshPeriod = 0 
     .TextFilePromptOnRefresh = False 
     .TextFilePlatform = 850 
     .TextFileStartRow = 1 
     .TextFileParseType = xlDelimited 
     .TextFileTextQualifier = xlTextQualifierDoubleQuote 
     .TextFileConsecutiveDelimiter = False 
     .TextFileTabDelimiter = True 
     .TextFileSemicolonDelimiter = False 
     .TextFileCommaDelimiter = False 
     .TextFileSpaceDelimiter = False 
     .TextFileOtherDelimiter = "|" 
     .TextFileColumnDataTypes = Array(1, 1, 1) 
     .TextFileTrailingMinusNumbers = True 
     .Refresh BackgroundQuery:=False 

    End With 

'Rename tabs to name on master list 
    ws.Name = "" & FileName(i) 

    Next i 

'Reopen the Report File 
    Workbooks.Open FileName:=ThisWorkbook.Path & "\Report.xlsx" 

End Sub 
Смежные вопросы