【问题标题】:Continue to next loop if file is not present in the current loop如果当前循环中不存在文件,则继续下一个循环
【发布时间】:2021-04-17 02:57:52
【问题描述】:

我在每个循环中打开一个文件,如果文件不存在,我必须跳过该循环并移至下一个,但不知何故我的代码不起作用。

For i = 1 To lngLstRowTemp    

  On Error Resume Next

  Set WrkBk_StateSummary = Application.Workbooks.Open(File_StateSummary)

  On Error GoTo 0

  If Not WrkBk_StateSummary Is Nothing Then

    Set WrkBk_StateSummary = Application.Workbooks.Open(File_StateSummary)       
         
    'Here I am opening the file WrkBk_StateSummary,
    'but if file is not present I want to goto next loop.

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您的代码示例不完整,但我希望您想要这个:

    For i = 1 To lngLstRowTemp
        If Len(Dir(File_StateSummary)) > 0 Then
            Set WrkBk_StateSummary = Application.Workbooks.Open(File_StateSummary)
        End If
    Next i
    

    它首先检查变量File_StateSummary中的文件是否存在,如果存在则打开它。

    如果这不是您需要的,请提供更多信息或更完整的代码。

    提示: 如果你想避免'箭头代码'(太多Ifs),那么你可以使用这个简洁的语法:VBA - how to conditionally skip a for loop iteration

    【讨论】:

    • 是的,所以如果文件不存在,它应该跳过这个循环(不要执行当前循环的下一步)并继续下一个循环
    • 那么问题已经回答了吗?
    • @karanarora:不客气。如果您发现它解决了您的问题,请考虑accepting the answer
    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 2022-12-17
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多