问题
My script is doing the following point :
- Retrieve all my selected folder files
- Class them by date (From the recent one to the older)
- Show them in a window
Here is my VBS Script (I retrieve it here):
Option Explicit
Const PathMDB = "C:\Users\C8461789\Desktop\test_script"
MsgBox TriRepertoire,,"Enumération " & PathMDB
'---lister les fichiers du répertoire ---
Function TriRepertoire()
Dim fso, fichier, fileItem
Dim i, imax, z, valeur, cible, liste
Set fso = CreateObject("Scripting.FileSystemObject")
imax = 0
'début de l'énumération
For Each fichier In fso.GetFolder(PathMDB).Files
Set fileItem = fso.GetFile(fichier)
imax = imax + 1
ReDim Preserve Tableau(2, imax)
Tableau(1, imax) = Fichier.Name
Tableau(2, imax) = FileItem.DateLastModified
'---trier les fichiers par ordre décroissant de création ---
Do
Valeur = 0
For i = 1 To imax - 1
If InStr(Tableau(1,i), "average", vbTextCompare) > 0 Then
If CDate(Tableau(2, i)) < CDate(Tableau(2, i + 1)) Then
For z = 1 To 2
Cible = Tableau(z, i)
Tableau(z, i) = Tableau(z, i + 1)
Tableau(z, i + 1) = Cible
Next
Valeur = 1
End If
End If
Next
Loop While Valeur = 1
Set fileItem = nothing
Next
'Affichage du résultat classé
For i = 1 To imax
'If IsNull(Tableau) Then
liste = liste &vbTab& Tableau(1, i) &vbCr
'End If
Next
TriRepertoire = liste
Set fso = nothing
End Function
In order to filter by name my retrieved files, I would like to add the following condition :
- For each file name, if it contains "average", add the file name to the table
- Else, do nothing
I tried to use
If InStr(Tableau(1,i), "average", vbTextCompare) > 0 Then
But it shows me this error :
回答1:
You are using InStr
incorrectly. Your code:
InStr(Tableau(1,i), "average", vbTextCompare)
The signature for InStr
is:
InStr([start,]string1,string2[,compare])
But the gotcha here is that it has two optional parameters, one of them being in the front, with a special condition:
Optional. Specifies the starting position for each search. The search begins at the first character position (1) by default. This parameter is required if compare is specified
So because you are using the fourth parameter with the value vbTextCompare
, you need to specify the starting point in the first parameter as well, which would be 1
(first character) in your case. So, the corrected code is:
InStr(1, Tableau(1,i), "average", vbTextCompare)
The error message you see basically complains that the first parameter is expected to be an integer, but you are feeding it a string.
See InStr docs.
来源:https://stackoverflow.com/questions/36864189/check-if-a-string-contains-specific-characters-using-vbs-script