如何使用字符串变量在vba中打开excel工作簿

时间:2015-01-15 03:22:50

标签: excel-vba vba excel

我有一系列Excel文件。我想将文件分配给字符串变量,然后将其分配给Workbooks.Open以打开它。我收到此错误"应用程序定义或对象定义的错误。知道我可能会出错吗?

这是我的代码:

Dim x As Workbook
Dim xFileName As String
Dim WkBk As Integer
Dim MyArrayOne as Integer
WkBk = 0

    MyArray1 = Array("filename1", filename2", filename3, filename4")

Do While Count <> MyArrayOne

    xFileName = MyArray1(WkBk)
    Set x = Workbooks.Open(xFileName)
    WkBk = WkBk + 1
Loop

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

Dim MyArray1 As Variant, i As Long, x As Workbook
MyArray1 = Array("filename_1", "filename_2", ... , "filename_n")

For i = LBound(MyArray1) To UBound(MyArray1)
    Set x = Workbooks.Open(MyArray1(i))
    'do other cool stuffs here
Next

答案 1 :(得分:0)

Sub M_snb()
    for each it in Array("filename1", "filename2", "filename3", "filename4")
        workbooks.open it
    next
End Sub