Macro to extract PNG image from file folder does not work on task scheduler

Hello!

I have a macro that sets the isometric view and saves an image in PNG format with the file name.

If I use the macro with a button inside the program, it works fine.

 

The problem is that it doesn't work with the task scheduler; it outputs a very small image and with a White background.

Does anyone know a way to make it work?

 

I have tried a lot of things and nothing works.

#If VBA7 Then
    Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Dim swApp As Object
Dim Part As Object
Dim fileSystem As Object
Dim folderPath As String
Dim file As Object
Dim fileName As String
Dim filePath As String
Dim fileExt As String
Dim docType As Long
Dim exportPath As String
Dim errors As Long
Dim warnings As Long
Dim exportData As Object

Const swDocPART = 1
Const swDocASSEMBLY = 2
Const swOpenDocOptions_Silent = 0
Const swExportPNG = 1


Const swTiffScreenOrPrintCapture = 1263
Const swTiffPrintDPI = 1264
Const swTiffPrintScaleFactor = 1265

Sub main()

    Set swApp = Application.SldWorks
    swApp.Visible = True

    Set fileSystem = CreateObject("Scripting.FileSystemObject")
    folderPath = "C:\\Users\\tirados\\Desktop\\PRUEBA MACRO CARPETA sw\\"  ' <-- 

    If Right(folderPath, 1) <> "\\" Then folderPath = folderPath & "\\"
    If Not fileSystem.FolderExists(folderPath) Then Exit Sub

    For Each file In fileSystem.GetFolder(folderPath).Files
        fileExt = LCase(fileSystem.GetExtensionName(file.Name))

        If fileExt = "sldprt" Or fileExt = "sldasm" Then
            docType = IIf(fileExt = "sldprt", swDocPART, swDocASSEMBLY)
            filePath = folderPath & file.Name
            Set Part = swApp.OpenDoc6(filePath, docType, swOpenDocOptions_Silent, "", errors, warnings)

            If Not Part Is Nothing Then
                Sleep 1000
                Part.ShowNamedView2 "*Isométrica", 7
                Part.ViewZoomtofit2
                Sleep 1000

                fileName = fileSystem.GetBaseName(file.Name)
                exportPath = folderPath & fileName & ".PNG"

               
                swApp.SetUserPreferenceIntegerValue swTiffScreenOrPrintCapture, 1
                swApp.SetUserPreferenceIntegerValue swTiffPrintDPI, 300
                swApp.SetUserPreferenceIntegerValue swTiffPrintScaleFactor, 1

                Set exportData = swApp.GetExportFileData(swExportPNG)

                Part.Extension.SaveAs exportPath, 0, 0, exportData, errors, warnings
                Sleep 1000
                swApp.CloseDoc file.Name
            End If
        End If
    Next

End Sub