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

时间:2016-11-20 16:14:03

标签: excel vba excel-vba for-loop

我想编写一个代码,根据条件打开多个.xlsx文件。我写了这个:

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

“Workbooks.Open ...”行无效。但是我只使用下一行(MsgBox)而不是“Workbooks.Open ...”,然后它完美地工作。

提前致谢

1 个答案:

答案 0 :(得分:0)

尝试以下代码。

打开文件后,您将丢失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