简体   繁体   中英

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. 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. However I use only the next line (MsgBox) instead of "Workbooks.Open...", then it is working perfectly.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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