2009-07-07 17 views

Respuesta

38

Mis comentarios sobre la respuesta de Renaud Bompuis se estropearon.

En realidad, puede utilizar el enlace tardío, y la referencia a la biblioteca de objetos 11.0 no es necesaria.

El siguiente código funcionará sin ninguna referencia:

Dim f As Object 
Set f = Application.FileDialog(3) 
f.AllowMultiSelect = True 
f.Show 

MsgBox "file choosen = " & f.SelectedItems.Count 

Tenga en cuenta que lo anterior funciona así en el tiempo de ejecución también.

+2

+1 Siempre esperé que esto fuera posible, la clave para hacer el último trabajo de enlace está pasando la opción numérica en lugar de msoOpenFileDialog, etc. Tan simple como una gran respuesta:) –

+0

Puede, pero no debería. Con el enlace tardío, está codificando en la oscuridad. Cuando agrega la referencia y declara y configura correctamente su objeto de archivo de archivo, el IDE le muestra sugerencias, mientras que con el enlace tardío no lo hará. – Chris

+1

@Chris OTOH, el uso del enlace anticipado significa que sus usuarios también deben tener las referencias agregadas. Eso significa que el enlace tardío es necesario para algunas aplicaciones. –

17

En Access 2007 solo necesita usar Application.FileDialog.

Aquí está el ejemplo de la documentación de acceso:

' Requires reference to Microsoft Office 12.0 Object Library. ' 
Private Sub cmdFileDialog_Click() 
    Dim fDialog As Office.FileDialog 
    Dim varFile As Variant 

    ' Clear listbox contents. ' 
    Me.FileList.RowSource = "" 

    ' Set up the File Dialog. ' 
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker) 

    With fDialog 

     ' Allow user to make multiple selections in dialog box ' 
     .AllowMultiSelect = True 

     ' Set the title of the dialog box. ' 
     .Title = "Please select one or more files" 

     ' Clear out the current filters, and add our own.' 
     .Filters.Clear 
     .Filters.Add "Access Databases", "*.MDB" 
     .Filters.Add "Access Projects", "*.ADP" 
     .Filters.Add "All Files", "*.*" 

     ' Show the dialog box. If the .Show method returns True, the ' 
     ' user picked at least one file. If the .Show method returns ' 
     ' False, the user clicked Cancel. ' 
     If .Show = True Then 

     'Loop through each file selected and add it to our list box. ' 
     For Each varFile In .SelectedItems 
      Me.FileList.AddItem varFile 
     Next 

     Else 
     MsgBox "You clicked Cancel in the file dialog box." 
     End If 
    End With 
End Sub 

Como dice la muestra, sólo asegúrese de que tiene una referencia a la Biblioteca de Acceso 12.0 Objeto Microsoft (bajo el IDE VBE> Herramientas> Referencias menú).

+0

En realidad, puede utilizar el enlace tardío, y la referencia a la biblioteca de objetos 11.0 no es necesaria. El siguiente código funcionará sin ninguna referencia: Dim f As Object conjunto F = f.AllowMultiSelect = f.Show Application.FileDialog (3) Verdadero MsgBox "archivo elegido =" & f.SelectedItems .Count Tenga en cuenta que lo anterior también funciona bien el tiempo de ejecución. Albert D.Kallal Edmonton, Alberta Canadá [email protected] –

+0

El ejemplo se copia desde aquí: http://support.microsoft.com/en-us/kb/824272 – Mike

2

adición a lo que Albert ya ha dicho:

Este código (un mashup de varias muestras) ofrece la posibilidad de tener un cuadro de diálogo Guardar como

Function getFileName() As String 
    Dim fDialog As Object 
    Set fDialog = Application.FileDialog(msoFileDialogSaveAs) 
    Dim varFile As Variant 

    With fDialog 
     .AllowMultiSelect = False 
     .Title = "Select File Location to Export XLSx :" 
     .InitialFileName = "jeffatwood.xlsx" 

    If .Show = True Then 
     For Each varFile In .SelectedItems 
     getFileName = varFile 
     Next 
    End If 
End With 
End Function 
+1

Esto es solo código para la misma respuesta que todos los demás han dado. Es más detallado y muestra más opciones, pero es solo una repetición de las respuestas existentes. –

+0

@ David-W-Fenton No, no lo es. Devuelve un nombre de archivo y le permite establecer un filtro, que ninguna de las otras respuestas lo hace. Está libre de dependencias de Office y se puede pegar directamente en cualquier forma o módulo, por lo que es plug and play. Esta es la mejor respuesta, y en cuanto a las otras respuestas, su crítica es aún más apta para las personas que copian/pegan de la documentación. –

0

estoy de acuerdo John M tiene mejor respuesta a OP pregunta. Aunque no se haya expresado explícitamente, el objetivo aparente es obtener un nombre de archivo seleccionado, mientras que otras respuestas devuelven recuentos o listas. Sin embargo, agregaría que el msofiledialogfilepicker podría ser una mejor opción en este caso. es decir:

Dim f As object 
Set f = Application.FileDialog(msoFileDialogFilePicker) 
dim varfile as variant 
f.show 
with f 
    .allowmultiselect = false 
    for each varfile in .selecteditems 
     msgbox varfile 
    next varfile 
end with 

Nota: el valor de varfile seguirá siendo el mismo desde multiselect es falsa (de una sola prenda cada vez seleccionado). Utilicé su valor fuera del ciclo con igual éxito. Sin embargo, es una mejor práctica hacerlo como lo hizo John M. Además, el selector de carpetas se puede usar para obtener una carpeta seleccionada. Siempre prefiero el enlace tardío, pero creo que el objeto es nativo de la biblioteca de acceso predeterminada, por lo que puede no ser necesario aquí

1

Tengo una solución similar a la anterior y funciona para abrir, guardar, seleccionar archivos. Lo pego en su propio módulo y lo uso en todos los DB de acceso que creo. Como el código indica que requiere Microsoft Office 14.0 Object Library. Solo otra opción, supongo:

Public Function Select_File(InitPath, ActionType, FileType) 
    ' Requires reference to Microsoft Office 14.0 Object Library. 

    Dim fDialog As Office.FileDialog 
    Dim varFile As Variant 


    If ActionType = "FilePicker" Then 
     Set fDialog = Application.FileDialog(msoFileDialogFilePicker) 
     ' Set up the File Dialog. 
    End If 
    If ActionType = "SaveAs" Then 
     Set fDialog = Application.FileDialog(msoFileDialogSaveAs) 
    End If 
    If ActionType = "Open" Then 
     Set fDialog = Application.FileDialog(msoFileDialogOpen) 
    End If 
    With fDialog 
     .AllowMultiSelect = False 
     ' Disallow user to make multiple selections in dialog box 
     .Title = "Please specify the file to save/open..." 
     ' Set the title of the dialog box. 
     If ActionType <> "SaveAs" Then 
      .Filters.Clear 
      ' Clear out the current filters, and add our own. 
      .Filters.Add FileType, "*." & FileType 
     End If 
     .InitialFileName = InitPath 
     ' 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 
     'Loop through each file selected and add it to our list box. 
      For Each varFile In .SelectedItems 
       'return the subroutine value as the file path & name selected 
       Select_File = varFile 
      Next 
     End If 
    End With 
End Function 
Cuestiones relacionadas