Найти часть каталога (без имени файла) полного пути в access 97 - PullRequest
20 голосов
/ 07 января 2009

По разным причинам я застрял в Access 97 и мне нужно получить только часть пути полного пути.

Например, имя

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

должно стать

c:\whatever dir\another dir\

На этом сайте есть несколько советов, как это сделать: http://www.ammara.com/access_image_faq/parse_path_filename.html

Но они кажутся довольно отвратительными. Должен быть лучший способ, верно?

Ответы [ 9 ]

34 голосов
/ 24 марта 2015

Вы можете сделать что-то простое, например: Left(path, InStrRev(path, "\"))

Пример:

Function GetDirectory(path)
   GetDirectory = Left(path, InStrRev(path, "\"))
End Function
19 голосов
/ 07 января 2009

Я всегда использовал FileSystemObject для такого рода вещей. Вот небольшая функция-обертка, которую я использовал. Обязательно укажите 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
10 голосов
/ 16 ноября 2012

Это похоже на работу. Выше не в 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
3 голосов
/ 07 января 2009

Вот и все. Нет волшебной встроенной функции ...

1 голос
/ 09 января 2009

Если вам просто нужен путь MDB, открытый в настоящее время в пользовательском интерфейсе Access, я бы предложил написать функцию, которая анализирует CurrentDB.Name и затем сохраняет результат в статической переменной внутри функции. Примерно так:

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

Преимущество состоит в том, что оно перебирает имя только один раз.

Конечно, он работает только с файлом, открытым в пользовательском интерфейсе.

Другой способ написать это - использовать функции, предоставленные по ссылке внутри функции выше, таким образом:

Public Function CurrentPath() As String
  Static strPath As String

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

Это делает поиск текущего пути очень эффективным при использовании кода, который можно использовать для поиска пути для любого имени файла / пути.

1 голос
/ 07 января 2009

левый (currentdb.Name, инстр (1, currentdb.Name, реж (currentdb.Name)) - 1)

Функция Dir будет возвращать только часть файла полного пути. Здесь используется currentdb.Name, но это может быть любая строка полного пути.

0 голосов
/ 28 февраля 2019

vFilename = "C: \ Informes \ Indicadores \ Program \ Ind_Cont_PRv.txt"

vDirFile = Заменить (vFilename, Dir (vFileName, vbDirectory), "")

'Результат = C: \ Informes \ Indicadores_Contraloria \ Programa \ Versiones anteriores \

0 голосов
/ 01 декабря 2014

Используйте эти коды и наслаждайтесь им.

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

И здесь вы можете вызвать функцию:

Sub test()
Dim s
For Each s In GetDirectoryName("C:\New folder")
Debug.Print s
Next
End Sub
0 голосов
/ 06 ноября 2013

Попробуйте эту функцию:

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

Если вы не хотите удалять последнюю обратную косую черту "\" в конце пути к папке, измените последнюю строку следующим образом:

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

Пример:

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

дает:

C: \ Users \ Christos \ Desktop \ LAT Analyzers Коррекция сигнала \ 1

или

C: \ Users \ Christos \ Desktop \ LAT Analyzers Коррекция сигнала \ 1 \

во втором случае (обратите внимание, что в конце есть обратный слеш).

Надеюсь, это поможет ...

...