Check if specifik folder exist.

H

HH

Hi'

I have a macro copying files to specifik folders. I only have one
problem, if the folder is not created then the script stops.

How do I let the script ignore this file at just move to the next? I
supose i need to check if the destination folder exist, but how?

Thanks.
 
S

Steve Rindsberg

Hi'

I have a macro copying files to specifik folders. I only have one
problem, if the folder is not created then the script stops.

How do I let the script ignore this file at just move to the next? I
supose i need to check if the destination folder exist, but how?

If Len(Dir$("C:\Temp", vbDirectory)) = 0 Then
MsgBox "Sorry ... no such directory"
Else
MsgBox "Found it."
End If
 
K

Karl E. Peterson

Steve said:
If Len(Dir$("C:\Temp", vbDirectory)) = 0 Then
MsgBox "Sorry ... no such directory"
Else
MsgBox "Found it."
End If

Dir is really frowned upon in the ClassicVB world, for "exists" tests. Lots
of potential pitfalls. Here's a method that avoids all of those...

Public Function FileExists(ByVal FileName As String) As Boolean
Dim nAttr As Long
' Grab this files attributes, and make sure it isn't a folder.
' This test includes cases where file doesn't exist at all.
On Error GoTo NoFile
nAttr = GetAttr(FileName)
If (nAttr And vbDirectory) <> vbDirectory Then
FileExists = True
End If
NoFile:
End Function

Public Function FolderExists(ByVal PathName As String) As Boolean
Dim nAttr As Long
' Grab the attributes, test valid values for folder bit.
On Error GoTo NoFolder
nAttr = GetAttr(PathName)
If (nAttr And vbDirectory) = vbDirectory Then
FolderExists = True
End If
NoFolder:
End Function

Folks with a religious aversion to Error trapping <g>, can drop in the API
equivalent...

Private Declare Function GetFileAttributes Lib "kernel32" Alias
"GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Const INVALID_FILE_ATTRIBUTES As Long = -1&
Private Const ERROR_SHARING_VIOLATION As Long = 32&

Public Function FileExists(ByVal FileName As String) As Boolean
Dim nAttr As Long
' Grab this files attributes, and make sure it isn't a folder.
' This test includes cases where file doesn't exist at all.
nAttr = GetFileAttributes(FileName)
If (nAttr And vbDirectory) <> vbDirectory Then
FileExists = True
ElseIf Err.LastDllError = ERROR_SHARING_VIOLATION Then
FileExists = True
End If
End Function

Public Function FolderExists(ByVal PathName As String) As Boolean
Dim nAttr As Long
' Grab the attributes, test valid values for folder bit.
nAttr = GetFileAttributes(PathName)
If nAttr <> INVALID_FILE_ATTRIBUTES Then
If (nAttr And vbDirectory) = vbDirectory Then
FolderExists = True
End If
End If
End Function

Fwiw... Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top