简体   繁体   English

vba 循环遍历工作簿

[英]vba loop through workbooks

Hi to everyone i have a problem and i can't understand why this does not work, here is the problem:大家好,我有一个问题,我不明白为什么这不起作用,这是问题所在:

i have a sub that do some stuff but before the sub begin i want to test if the workbooks needed are present in the folder they are 4 so i can do one by one but i think there are better solutions so i came up with this我有一个做一些事情的子,但是在子开始之前,我想测试所需的工作簿是否存在于文件夹中,它们是 4,所以我可以一个一个地做,但我认为有更好的解决方案,所以我想出了这个

**Sub test()

Dim link1, link2, link3, link4 As String
link1 = "C:\Users\Cristiano\Desktop\prove excel\loco.xlsx"
link2 = "C:\Users\Cristiano\Desktop\prove excel\668.xlsx"
link3 = "C:\Users\Cristiano\Desktop\prove excel\mezzi leggeri.xlsx"
link4 = "C:\Users\Cristiano\Desktop\prove excel\blocci vetture.xlsx"

For r = 1 To 4
   If Dir(link & r) = "" Then
    MsgBox "file not found in the path"&" "& link & r
    End If
Next r

end sub**

but it does not work, if it was possible i would like to put just the missing file in a unique msgbox但它不起作用,如果可能的话,我只想把丢失的文件放在一个独特的 msgbox 中

what i am doing wrong?我做错了什么?

thanks in advance提前致谢

  • Use Option Explicit which will force you to declare all variables ( r ).使用Option Explicit将强制您声明所有变量( r )。

  • When declaring variables in one line, every variable has to have an As :在一行中声明变量时,每个变量都必须有一个As

     Dim link1 As String, link2 As String, link3 As String, link4 As String
  • You can write the file paths to an array .您可以将文件路径写入数组

The Code编码

Option Explicit

Sub test()

    Dim Paths(1 To 4) As String
    Paths(1) = "C:\Users\Cristiano\Desktop\prove excel\loco.xlsx"
    Paths(2) = "C:\Users\Cristiano\Desktop\prove excel\668.xlsx"
    Paths(3) = "C:\Users\Cristiano\Desktop\prove excel\mezzi leggeri.xlsx"
    Paths(4) = "C:\Users\Cristiano\Desktop\prove excel\blocci vetture.xlsx"
    
    Dim r As Long
    For r = 1 To 4
        If Dir(Paths(r)) = "" Then
            MsgBox "File '" & Paths(r) & "' not found."
        End If
    Next r

End Sub

Here's another one:这是另一个:

Sub test2()
    Dim mat(1 To 4) As String
    mat(1) = "C:\Users\Cristiano\Desktop\prove excel\loco.xlsx"
    mat(2) = "C:\Users\Cristiano\Desktop\prove excel\668.xlsx"
    mat(3) = "C:\Users\Cristiano\Desktop\prove excel\mezzi leggeri.xlsx"
    mat(4) = "C:\Users\Cristiano\Desktop\prove excel\blocchi vetture.xlsx"
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim r As Long
    Dim msg As Object
    Set msg = CreateObject("System.Collections.ArrayList")
    For r = 1 To 4
        If Not fso.FileExists(mat(r)) Then
            msg.Add fso.GetFileName(mat(r))
        End If
    Next r
    msg.Sort
    Dim arr As Variant
    arr = msg.ToArray
    MsgBox Join(arr, vbLf)
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM