I try to create vba code that create a zip-file that contains all file in a sourcefolder, and I get problems when I try to create Shell objects (objFolder and objZipFolder). It works fine when I hardcode (Set objFolder = objShell.Namespace("C:.....")). But when I use a variable (Set objFolder = objShell.Namespace(fldPth)), objFolder return "Nothing". In the code below I have included the possibilities I have tried, and made comments of the results after each line. I would be grateful for any solutions that might work.
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim objShell As Object
Dim objFolder As Object 'SourceFolder
Dim objZipFile As Object 'ZipFolder
Dim fldPth As String
Dim zipFldPth As String
fldPth = "C:\Users\bruker\Desktop\MyFolder"
zipFldPth = "C:\Users\bruker\Desktop\Archive.zip"
If FSO.FileExists(zipFldPth) Then FSO.DeleteFile zipFldPth 'Delete old ZipFile
FSO.CreateTextFile zipFldPth 'Create new ZipFile
'Check if the paths exists
If Not FSO.FolderExists(fldPth) Then Exit Sub 'OK
If Not FSO.FileExists(zipFldPth) Then Exit Sub 'OK
'Create objects
Set objShell = CreateObject("Shell.Application")
'objFolder:
Set objFolder = objShell.Namespace(fldPth) 'Return: objFolder = Nothing
'Set objFolder = objShell.Namespace("C:\Users\bruker\Desktop\MyFolder") 'Return: objFolder = "MyFolder" OK
'Set objFolder = objShell.Namespace(Chr(34) & fldPth & Chr(34)) 'Return: objFolder = Nothing
'Set objFolder = objShell.Namespace("""" & fldPth & """") 'Return: objFolder = Nothing
'Set objFolder = objShell.Namespace(fldPth).Self 'Run-time error 91
'Set objFolder = GetObject(fldPth) 'Run-time error 432
'objZipFile:
Set objZipFile = objShell.Namespace(zipFldPth) 'Return: objZipFile = Nothing
'Set objZipFile = objShell.Namespace("C:\Users\bruker\Desktop\Archive.zip") 'Return: ojbZipFile = "Archive.zip" OK
'Set objZipFile = objShell.Namespace(Chr(34) & zipFldPth & Chr(34)) 'Return: objZipFile = Nothing
'Set objZipFile = objShell.Namespace("""" & zipFldPth & """") 'Return: objZipFile = Nothing
'Set objZipFile = objShell.Namespace(zipFldPth).Self 'Run-time error 91
'Set objZipFile = GetObject(zipFldPth) 'Run-Time error 430
If objFolder Is Nothing Or objZipFile Is Nothing Then 'Check that the Shell objects were created successfully
MsgBox "Could not create Shell objects.", vbCritical 'THIS LINE IS ACTIVATED. objFolder and objZipFile returne "Nothing"
Exit Sub
End If
objZipFile.CopyHere objFolder.Items 'Copy the folder items to the zip file
' Clean up objects
Set objZipFile = Nothing
Set objFolder = Nothing
Set objShell = Nothing
Set FSO = Nothing