打印文件夹VBA代码中的所有文件不起作用

时间:2019-04-08 10:34:57

标签: excel vba excel-2007

我正在尝试使用此代码打印文件夹中的所有文件,但某些功能无法正常运行...

Sub Bulk_Print_From_Folder()

Dim k       As Variant
Dim n       As Variant
Dim oFile   As Object
Dim oFiles  As Object
Dim oFolder As Object
Dim Path    As Variant
Dim vItem   As Object

    Path = "C:\Testing Folder"

    With CreateObject("Shell.Application")
        Set oFolder = .Namespace(Path)
        If oFolder Is Nothing Then
            MsgBox "The Folder :" & vbLf & """" & Path & """ was Not Found.", vbCritical
            Exit Sub
        End If
    End With

    Set oFiles = oFolder.Items
        oFiles.Filter 64, "*.pdf;*.jpg;*.png;*.txt"

        For n = 0 To oFiles.Count - 1
            Set oFile = oFiles.Item(n)
            For k = 0 To oFile.Verbs.Count - 1
                Set vItem = oFile.Verbs.Item(k)
                If Not vItem Is Nothing Then
                    If Replace(vItem, "&", "") = "Print" Then vItem.DoIt
                End If
            Next k
        Next n

     End Sub

其他信息:

»»我启用了宏并定义了默认打印机...打印机正常工作。

»»我注意到单击按钮执行此代码后,在任务栏中没有看到打印机图标。而且如果可以的话,我正在使用Office 2007 Ultimate。

»»我知道它找到了文件夹。我通过更改代码上的文件夹名称进行测试,然后收到消息

MsgBox "The Folder :" & vbLf & """" & Path & """ was Not Found.", vbCritical

这是我的项目参考:

enter image description here

我想念什么吗?

1 个答案:

答案 0 :(得分:2)

There is nothing wrong with the code.

The problem is with the default program set for opening the image file. If you right click on the image file, you will not see the Print option. To sort this issue, open Control panel and go to Default Apps. Change the default app of Photo Viewer to say Paint. Close Default Apps

Now right click on the image file and you will see the Print option. If you do see Print, then your code will now run as vItem will have &Print

If you have a mix of files in that folder and you do not see a Print option for any particular extention then do what I suggested above. Change the default app till you see the Print in the context menu.

Depending on OS, you may see &Print or &Print out or something in a regional language. You can test that by using this code

For n = 0 To oFiles.Count - 1
    Set oFile = oFiles.Item(n)
    For k = 0 To oFile.Verbs.Count - 1
        Set vItem = oFile.Verbs.Item(k)
        If Not vItem Is Nothing Then
            Debug.Print vItem
        End If
    Next k
Next n

So you may want to change the code

If Replace(vItem, "&", "") = "Print" Then

to

If InStr(1, vItem, "&Print") Then 

or to

InStr(1, vItem, "imprimir", vbTextCompare) '<~~ See Chat below quesiton