简体   繁体   English

如何在VBA中使用IF打开文件

[英]how to open a file using IF in VBA

I would like to write a code which open more than one .xlsx files, depending the conditions. 我想写一个代码,根据情况打开多个.xlsx文件。 I wrote this one: 我写了这个:

Sub Macro()
    Dim ColumnNumb As Integer
    Dim FileName(14 To 16) As String
    Dim i As Integer
    ColumnNumb = 2

    For i = 14 To 16
        FileName(i) = Cells(i, 1).Value
        If Workbooks("Book1.xlsm").Worksheets("Input").Cells(14, ColumnNumb) = "Yes" Then
            Workbooks.Open FileName:="C:\Excel\" & FileName(i), UpdateLinks:=3
            'MsgBox FileName(i)
         End If
    Next i 
End Sub

The "Workbooks.Open..." line which is not working. “ Workbooks.Open ...”行不起作用。 However I use only the next line (MsgBox) instead of "Workbooks.Open...", then it is working perfectly. 但是,我只使用下一行(MsgBox)而不是“ Workbooks.Open ...”,所以它工作正常。

Thanks in advance 提前致谢

Try the code below. 试试下面的代码。

Once you open the File you lose your ActiveSheet , so the line FileName(i) = Cells(i, 1).Value won't work on the second time. 打开文件后,您将失去ActiveSheet ,因此行FileName(i) = Cells(i, 1).Value在第二次将不起作用。

Sub Macro()

Dim ColumnNumb As Integer
Dim FileName(14 To 16) As String
Dim i As Integer
Dim ThisWB  As Workbook
Dim Sht As Worksheet

ColumnNumb = 2

Set ThisWB = ThisWorkbook
' I assume from your post your data is in "Input" sheet >> modify to your needs
Set Sht = ThisWB.Sheets("Input")

For i = 14 To 16
    FileName(i) = Sht.Cells(i, 1).Value

    If Sht.Cells(14, ColumnNumb) = "Yes" Then
        Workbooks.Open FileName:="C:\Excel\" & FileName(i), UpdateLinks:=3
        'MsgBox FileName(i)
    End If
Next i

End Sub

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

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