2009-01-06 17 views
18

Por diversas razones, estoy atrapado en Access 97 y necesito obtener solo la ruta de acceso de una ruta de acceso completa.Busque la parte del directorio (menos el nombre del archivo) de una ruta completa en el acceso 97

Por ejemplo, el nombre

c:\whatever dir\another dir\stuff.mdb 

debe convertirse en

c:\whatever dir\another dir\ 

Este sitio tiene algunas sugerencias sobre cómo hacerlo: http://www.ammara.com/access_image_faq/parse_path_filename.html

pero parecen más bien horrible. Debe haber una mejor manera, ¿verdad?

+0

¿Cuál es horrible al respecto? Parece un código bastante simple para mí, y tenía mis propias versiones escritas para A97 que todavía se ejecutan en aplicaciones de hoy, a pesar de que proporcionan mejores funciones integradas de las que estaban disponibles en A97. –

+0

Se ha eliminado de las preguntas: ¿CurrentProject.Path está disponible en Access 97? – Fionnuala

+1

Respuesta: No, CurrentProject falta por completo en Access 97. Sin embargo, CurrentDb.Name, pero esa es la ruta completa, incluido el nombre del archivo. - apenwarr – Fionnuala

Respuesta

1

Eso es todo. No hay una función mágica incorporada ...

16

Siempre he usado el FileSystemObject para este tipo de cosas. Aquí hay una pequeña función de envoltura que utilicé. Asegúrese de hacer referencia al Microsoft Scripting Runtime.

Function StripFilename(sPathFile As String) As String 

'given a full path and file, strip the filename off the end and return the path 

Dim filesystem As New FileSystemObject 

StripFilename = filesystem.GetParentFolderName(sPathFile) & "\" 

Exit Function 

End Function 
+2

Mala idea, porque requiere una referencia al trabajo. Si insistes en ello, debes usar el enlace tardío. –

+9

¿Desde cuándo son las referencias una mala idea? El acceso en sí requiere referencias al trabajo. 0_o –

+0

Esto funciona muy bien en vba. Lo único que tenía que hacer era convertir el sistema de archivos en un objeto normal y luego configurarlo en el tipo completo de FileSystemObject – MattCucco

1

izquierda (currentdb.Name, Instr (1, currentdb.Name, dir (currentdb.Name)) - 1)

La función Dir devolverá sólo la parte del archivo de la ruta completa. Currentdb.Name se usa aquí, pero podría ser cualquier cadena de ruta completa.

+0

Hmm, parece que no funcionaría si la parte del nombre de archivo aparece como parte de la ruta, por ejemplo. "c: \ whatever.txt \ x \ y \ z \ whatever.txt" se dividiría incorrectamente. – apenwarr

+3

Correcto. Editaré mi respuesta tan pronto como eso me ocurra a mí o a cualquier persona que conozca. Hasta ahora no ha sido así. –

1

Si solo necesita la ruta del MDB actualmente abierto en la IU de acceso, le sugiero que escriba una función que analice CurrentDB.Name y luego almacene el resultado en una variable estática dentro de la función. Algo como esto:

Public Function CurrentPath() As String 
    Dim strCurrentDBName As String 
    Static strPath As String 
    Dim i As Integer 

    If Len(strPath) = 0 Then 
    strCurrentDBName = CurrentDb.Name 
    For i = Len(strCurrentDBName) To 1 Step -1 
     If Mid(strCurrentDBName, i, 1) = "\" Then 
      strPath = Left(strCurrentDBName, i) 
      Exit For 
     End If 
    Next 
    End If 
    CurrentPath = strPath 
End Function 

Esto tiene la ventaja de que solo recorre el nombre una vez.

Por supuesto, solo funciona con el archivo que está abierto en la interfaz de usuario.

Otra forma de escribir esto sería el uso de las funciones previstas en el link dentro de la función anterior, así:

Public Function CurrentPath() As String 
    Static strPath As String 

    If Len(strPath) = 0 Then 
    strPath = FolderFromPath(CurrentDB.Name) 
    End If 
    CurrentPath = strPath 
End Function 

Esto hace que la recuperación de la trayectoria de corriente muy eficiente mientras que la utilización de código que puede ser usado para encontrar la ruta para cualquier nombre de archivo/ruta.

10

Esto parece funcionar. Lo anterior no aparece en Excel 2010.

Function StripFilename(sPathFile As String) As String 
'given a full path and file, strip the filename off the end and return the path 
Dim filesystem As Object 

Set filesystem = CreateObject("Scripting.FilesystemObject") 

StripFilename = filesystem.GetParentFolderName(sPathFile) & "\" 

Exit Function 

End Function 
+0

Las referencias también pueden establecerse en Excel VBA. En el editor de VBA, haga clic en el menú Herramientas y luego en Referencias. Marque la casilla en la lista al lado de "Microsoft Scripting Runtime". El tipo FileSystemObject debería estar disponible para declarar en la instrucción Dim. –

+0

Esta es básicamente la misma función publicada por @Siddharth Rout, pero funciona sin una referencia a la biblioteca "Microsoft Scripting Runtime". – ChrisB

0

Pruebe esta función:

Function FolderPath(FilePath As String) As String 

    '-------------------------------------------------- 
    'Returns the folder path form the file path. 

    'Written by: Christos Samaras 
    'Date:   06/11/2013 
    '-------------------------------------------------- 

    Dim FileName As String 

    With WorksheetFunction 
     FileName = Mid(FilePath, .Find("*", .Substitute(FilePath, "\", "*", Len(FilePath) - _ 
        Len(.Substitute(FilePath, "\", "")))) + 1, Len(FilePath)) 
    End With 

    FolderPath = Left(FilePath, Len(FilePath) - Len(FileName) - 1) 

End Function

Si no desea eliminar la última barra invertida "\" al final de la ruta de la carpeta, cambiar la última línea con esto:

FolderPath = Left(FilePath, Len(FilePath) - Len(FileName))

Ejemplo:

FolderPath("C:\Users\Christos\Desktop\LAT Analysers Signal Correction\1\TP 14_03_2013_5.csv") 

da:

C: \ Users \ Corrección Christos \ Desktop \ LAT analizadores de señal \ 1

o

C: \ Users \ Corrección Christos \ Desktop \ LAT analizadores de señal \ 1 \

en el segundo caso (tenga en cuenta que hay una barra invertida al final).

Espero que ayude ...

-1

Utilice estos códigos y disfrútelo.

Public Function GetDirectoryName(ByVal source As String) As String() 
Dim fso, oFolder, oSubfolder, oFile, queue As Collection 
Set fso = CreateObject("Scripting.FileSystemObject") 
Set queue = New Collection 

Dim source_file() As String 
Dim i As Integer   

queue.Add fso.GetFolder(source) 'obviously replace 

Do While queue.Count > 0 
    Set oFolder = queue(1) 
    queue.Remove 1 'dequeue 
    '...insert any folder processing code here... 
    For Each oSubfolder In oFolder.SubFolders 
     queue.Add oSubfolder 'enqueue 
    Next oSubfolder 
    For Each oFile In oFolder.Files 
     '...insert any file processing code here... 
     'Debug.Print oFile 
     i = i + 1 
     ReDim Preserve source_file(i) 
     source_file(i) = oFile 
    Next oFile 
Loop 
GetDirectoryName = source_file 
End Function 

Y aquí se puede llamar a la función:

Sub test() 
Dim s 
For Each s In GetDirectoryName("C:\New folder") 
Debug.Print s 
Next 
End Sub 
26

se puede hacer algo tan simple como: Left(path, InStrRev(path, "\"))

Ejemplo:

Function GetDirectory(path) 
    GetDirectory = Left(path, InStrRev(path, "\")) 
End Function 
+0

Campeón !! La mejor solución de lejos! –

Cuestiones relacionadas