FAQ MS-Access

FAQ MS-AccessConsultez toutes les FAQ
Nombre d'auteurs : 140, nombre de questions : 926, dernière mise à jour : 15 juin 2021
Sommaire→Fichiers et répertoires- Comment utiliser FileSystemObject ?
- Comment lire un fichier XML ?
- Comment gérer mes fichiers avec Access (objets OLE) ?
- Comment travailler sur un fichier texte (création, lecture, écriture...) ?
- Comment avec l'API GetOpenFileNameA ouvrir plusieurs fichiers à la fois ?
- Comment compter les occurrences d'une chaîne dans un fichier ?
- Comment obtenir le chemin relatif d'un fichier ?
- Comment tester l'existence d'un fichier ?
9.1. Création/Suppression/Modifications
(11)
9.2. Recherches et Localisation
(13)
9.3. Informations
(9)
Ajoutez la bibliothèque Microsoft Scripting Runtime. Le fichier correspondant se nomme scrrun.dll
Lien : FAQ VB
La lecture d'un fichier XML se fait à l'aide d'un parseur. Dans les références du projet, ajoutez Microsoft XML.
Voici un exemple qui affiche dans la fenêtre de débogage la liste des balises contenues dans un document XML.
Private Sub BrowseChildNodes(root_node As IXMLDOMNode)
Dim i As Long
For i = 0 To root_node.childNodes.length - 1
If root_node.childNodes.Item(i).nodeType <> 3 Then Debug.Print root_node.childNodes.Item(i).baseName
BrowseChildNodes root_node.childNodes(i)
Next
End Sub
Private Sub BrowseXMLDocument(ByVal filename As String)
Dim xmlDoc As DOMDocument, root As IXMLDOMElement
Set xmlDoc = New DOMDocument
xmlDoc.async = False
xmlDoc.Load filename
Set root = xmlDoc.documentElement
If Not root Is Nothing Then
Debug.Print root.baseName
BrowseChildNodes root
End If
End SubAppelez simplement la procédure BrowseXMLDocument en passant en paramètre le chemin du fichier. Cette procédure ouvre
le fichier puis appelle la procédure BrowseChildNodes qui parcourt l'ensemble des balises de façon récursive.
------------------------------------------------------------------------------------------------
Pour modifier une valeur :
root_node.childNodes.Item(i).Text = "Lou Pitchoun"Pour sauvegarder :
xmlDoc.Save "Chemin + nom fichier"Ce code donne le nom de la balise :
Debug.Print root_node.childNodes.Item(i).baseNameLien : FAQ VB
Lien : Repousser les limites d'Access - récupérer un fil RSS
Lien : Visual Basic 6.0 et le format XML
On a souvent parlé des images en disant qu'il valait mieux éviter de les stocker dans la base de données. Ceci est valable pour tous les objets OLE.
Un OS (Système d'Exploitation) est prévu pour gérer les fichiers. Les stocker à l'extérieur de la base de données pour ne stocker dans la base que le chemin d'accès donnera souvent de bien meilleurs résultats.
Exemple d'utilisation du chemin stocké grâce à une API :
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Long) As LongPuis dans le code on l'appelle ainsi :
ShellExecute Me.hWnd, vbNullString, CheminduFichier, "", vbNullString, 1Lien : Comment ouvrir un fichier HTML, Word, PDF ou autre en utilisant l'exécutable associé ?
Lien : Que faire quand l'API ShellExecute ne fonctionne pas ?
Lire un fichier :
Function LireFichier(ByVal sPath As String) As String()
Dim fso As FileSystemObject
Dim fFile As File
Dim ts As TextStream
Dim result As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set fFile = fso.GetFile(sPath)
Set ts = fFile.OpenAsTextStream(ForReading)
result = ts.ReadAll
LireFichier = Split(result, vbCrLf)
ts.Close
Set ts = Nothing
Set fFile = Nothing
Set fso = Nothing
End FunctionCréer un fichier :
Function CreerFichier(ByVal sPath As String)
Dim fso As FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile sPath
Set fso = Nothing
End FunctionAjouter une ligne :
Function AjoutLigneDansFichier(ByVal sPath As String, ByVal sTexte As String)
Dim fso As FileSystemObject
Dim fFile As File
Dim ts As TextStream
Set fso = CreateObject("Scripting.FileSystemObject")
Set fFile = fso.GetFile(sPath)
Set ts = fFile.OpenAsTextStream(ForAppending)
ts.WriteLine sTexte
ts.Close
Set ts = Nothing
Set fFile = Nothing
Set fso = Nothing
End FunctionIl suffit de mettre l'attribut flags à la valeur suivante :
openfile.flags = &H200 'MultiselectEnsuite, la variable fichier est un string qui va contenir les noms.
C:\autoexec.bat nouveau.txtÀ vous de travailler cette chaîne pour obtenir le résultat souhaité.
Lien : Rétablir les liaisons des tables liées après déplacement d'une base fractionnée
Lien : Comment afficher la boîte de dialogue Ouvrir afin de récupérer le nom et le chemin du fichier sélectionné ?
C'est faisable grâce aux RegExp. Pensez toutefois à ajouter la référence Microsoft Regular Expressions 5.5 :
Function CountMatches(ByVal strFic As String, ByVal strSearch As String) As Long
Dim reg As VBScript_RegExp_55.RegExp
Dim Matches As VBScript_RegExp_55.MatchCollection
Dim Fic As Integer
Dim strBuff As String * 20000
Dim strBorder As String
' Instanciation
Set reg = New VBScript_RegExp_55.RegExp
reg.Global = True
reg.IgnoreCase = True
reg.Multiline = True
reg.Pattern = "(" & strSearch & ")"
' Gestion fichier
Reset
Fic = FreeFile
Open strFic For Binary Access Read As #Fic
Do While Not EOF(Fic)
strBorder = Right(strBuff, Len(strSearch) - 1)
Get #Fic, , strBuff
strBorder = strBorder & strBuff
Set Matches = reg.Execute(strBorder)
CountMatches = CountMatches + Matches.Count
Loop
Close #Fic
' Libération
Set reg = Nothing
Set Matches = Nothing
End FunctionExemple :
?countmatches("c:\temp\long.txt"," ")
7500Lien : Les expressions rationnelles et Access par la pratique
Pour obtenir le chemin relatif d'un fichier par rapport à un répertoire, vous pouvez utiliser la fonction suivante :
Function GetRelativePath(ByVal strPath As String, Optional ByVal strPathCurrent As String)
Dim tmpCurr() As String
Dim tmpP() As String
Dim i As Integer
Dim iIndex As Integer
' Par défaut, on considère que c'est relatif par rapport au chemin courant de la base
If strPathCurrent = "" Then strPathCurrent = CurrentProject.Path
If Right(strPathCurrent, 1) = "\" Then strPathCurrent = Left(strPathCurrent, Len(strPathCurrent) - 1)
If Left(strPath, 1) = Left(strPathCurrent, 1) Then
' On recherche la partie commune aux deux chemins
tmpP = VBA.Split(strPath, "\")
tmpCurr = VBA.Split(strPathCurrent, "\")
For iIndex = 0 To IIf(UBound(tmpP) > UBound(tmpCurr), UBound(tmpCurr), UBound(tmpP))
If tmpP(iIndex) <> tmpCurr(iIndex) Then
Exit For
Else
i = iIndex
End If
Next iIndex
If i = UBound(tmpCurr) Then
' C'est un sous-répertoire
For iIndex = i + 1 To UBound(tmpP)
GetRelativePath = GetRelativePath & tmpP(iIndex) & "\"
Next iIndex
GetRelativePath = Left(GetRelativePath, Len(GetRelativePath) - 1)
Else
' Il faut remonter de UBound(tmpCurr) - i
For iIndex = 1 To UBound(tmpCurr) - i
GetRelativePath = GetRelativePath & "..\"
Next iIndex
For iIndex = i + 1 To UBound(tmpP)
GetRelativePath = GetRelativePath & tmpP(iIndex) & "\"
Next iIndex
GetRelativePath = Left(GetRelativePath, Len(GetRelativePath) - 1)
End If
Else
' Deux lecteurs différents
GetRelativePath = strPath
End If
End FunctionLe premier paramètre correspond au chemin du fichier ou du dossier, le second correspond au chemin courant.
Exemple :
?getrelativepath("c:\toto\tata\test.xls","c:\tintin")
..\toto\tata\test.xls
?getrelativepath("c:\toto\tata\test.xls","c:\toto\tata")
\test.xlsCette fonction permet de tester l'existence d'un fichier, elle renvoie True si le fichier existe :
Function existeFileFSO(ByVal fichier As String) As Boolean
Set fs = CreateObject("Scripting.FileSystemObject")
existeFileFSO = fs.FileExists(fichier)
Set fs = Nothing
End Function
Autre méthode en passant par les API :
Declare Function SearchPath Lib "kernel32" Alias "SearchPathA" (ByVal lpPath As String, ByVal lpFileName As String, ByVal lpExtension As String, ByVal nBufferLength As Long, ByVal lpBuffer As String, ByVal lpFilePart As String) As Long
Function existeFileSearchPath(ByVal chemin, fichier As String) As Boolean
' Nécessite Windows Vista, Windows XP, or Windows 2000 Professional.
Dim ResultFileName As String
Dim pFilePart As Long
existeFileSearchPath = SearchPath(chemin, fichier, vbNullString, 1, ResultFileName, pFilePart) > 0
End Function


