Как взять просматриваемый текстовый файл и поместить его в список VBA - PullRequest
0 голосов
/ 06 мая 2011

Так что я новичок в использовании access / VBA, и у меня возникают проблемы с этим.

Private Sub Get_File_Click()

    Dim fdlg As Office.FileDialog
    Dim pipe_file As Variant
    Dim FileName As String
    Dim file As String
    Dim fn As Integer

    ' Clear contents of listboxes and textboxes. '
    Me.OrigFile.RowSource = ""
    Me.ConvertFile.RowSource = ""
    Me.FileName = ""

    ' Set up the File dialog box. '
    Set fdlg = Application.FileDialog(msoFileDialogFilePicker)
    With fdlg
        .AllowMultiSelect = False

        ' Set the title of the dialog box. '
        .Title = "Select pipe delimited file" 

        ' Clear out the current filters, and then add your own. '
        .Filters.Clear
        .Filters.Add "Text Files", "*.txt"


        ' Show the dialog box. If the .Show method returns True, the '
        ' user picked a file. If the .Show method returns            '
        ' False, the user clicked Cancel.                            '
        If .Show = True Then
            file = fdlg
            fn = FreeFile
            Open file For Input As #fn
            Do While Not EOF(fn)
                Line Input #fn, pipe_file
                Me.OrigFile.AddItem pipe_file
            Loop
        Else
            MsgBox "You clicked Cancel in the file dialog box."
        End If
    End With
End Sub

Это то, что я имею до сих пор. origFile - это список, в который я пытаюсь поместить текстовый файл. Любая помощь приветствуется Спасибо

Ответы [ 2 ]

0 голосов
/ 07 мая 2011

Комментарии добавлены Встроенные:

Private Sub Get_File_Click()

    Dim fdlg As Office.FileDialog
    Dim pipe_file As Variant
    'Why two vars named 'FileName' and 'file'?  Since they are both string, assuming just one of these will do.
    Dim FileName As String
    'Dim file As String
    Dim fn As Integer
    'Need variant variable to get file name
    Dim varFile As Variant

    Me.OrigFile.RowSource = ""
    Me.ConvertFile.RowSource = ""

    'Don't use ME here.  Unless you have an object named FileName (which I'm not sure why you would in this case)
    'Me.FileName = ""
    FileName = ""

    Set fdlg = Application.FileDialog(msoFileDialogFilePicker)
    With fdlg
        .AllowMultiSelect = False
        .Title = "Select pipe delimited file"
        .Filters.Clear
        .Filters.Add "Text Files", "*.txt"

        If .Show = True Then
            'Never used this code before but this is how you get the file name:
            'Seems lame to have three lines of code to get one file name, but I guess this is the way this control works
            For Each varFile In .SelectedItems
                FileName = varFile
            Next varFile

            'The invalid code below was causing the error and it is no longer necessary.
            'However, also wanted to point out that you are already in a With block for fldg so the fdlg object is not required

            'FileName = fdlg.SelectedItems

            fn = FreeFile 'FreeFile = Good!

            'Commented out the line below because file is not used

            'Open file For Input As #fn
            Open FileName For Input As #fn
            Do While Not EOF(fn)
                Line Input #fn, pipe_file
                Me.OrigFile.AddItem pipe_file
            Loop

            'Make sure to close the file too!
            Close #fn
        Else
            MsgBox "You clicked Cancel in the file dialog box."
        End If
    End With
End Sub

Также, один последний совет, убедитесь, что в верхней части ваших модулей объявлена ​​следующая строка кода:

Option Explicit

Это будетпредотвратить случайный ввод неправильного имени переменной.

Проект VBA можно добавить в эту строку по умолчанию, если нажать «Инструменты / Параметры», а затем выбрать «Требовать объявление переменной» на вкладке «Редактор»..

0 голосов
/ 07 мая 2011

Я думаю, что ваша проблема в строке

file = fdlg

должно быть

file = fdlg.SelectedItems(1)
...