VB宏 - 每个循环运行时错误“13”

时间:2011-02-28 12:15:20

标签: excel vba excel-vba

我知道可能有这样的问题。但我真的不熟悉VB,所以我需要帮助。以下是代码的一部分:

    Sub Convert_to_Digi()

    Dim SrcWkb As Workbook
    Dim csvWkb As Workbook
    Dim srcSheet As Worksheet
    Dim StartRow As Long
    Dim wkbname As Variant
    Dim xlsFiles As Variant
    Dim MyRange As Range
    Dim NewName As Variant
    Dim csvName As String

    StartRow = 2

    ' Get the workbooks to open
    xlsFiles = Application.GetOpenFilename(FileFilter:="Excel files (*.xls), *.xls", MultiSelect:=True)
    If VarType(xlsFiles) = vbBoolean Then Exit Sub

    ' Loop through each workbook and copy the data to this CSV
     For Each wkbname In xlsFiles
        Set SrcWkb = Workbooks.Open(Filename:=wkbname, ReadOnly:=False)
        Set srcSheet = SrcWkb.Worksheets("export_label_conf")

        ' Get used range on sheet
        Set MyRange = srcSheet.UsedRange
        ' Adjust to exclude top row
        Set MyRange = MyRange.Offset(1, 0).Resize(MyRange.Rows.Count - 1)

        NewName = srcSheet.Cells(2, 10) & ".csv"

        If MyRange.Row + MyRange.Rows.Count - 1 >= StartRow Then
            Set csvWkb = Workbooks.Open(Filename:="C:\DIGITAL\template.csv", ReadOnly:=False)

            ' copy column A
            MyRange.Columns(1).Copy
            ' paste into CSV template file, column I
            csvWkb.ActiveSheet.Cells(2, 9).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
                SkipBlanks:=False, Transpose:=False

            ' and save template as new CSV with barcode as name
            csvName = "C:\DIGITAL\" & NewName
            csvWkb.SaveAs Filename:=csvName, FileFormat:=xlCSV, CreateBackup:=False
        End If

        SrcWkb.Close
    Next wkbname

End Sub

我在 每个wkbname在xlsFiles 行中出现此错误。 wkbname是空的,而xlsFiles包含要打开的文件的名称(但只有1,而它应该有几个......)

并且不久前它工作正常!我完全忘记了我所做的一切,但没有解决问题......

1 个答案:

答案 0 :(得分:0)

我建议你这样做:

  • 尝试编译代码。听起来很虚伪,但可能会在其他地方指出可能会影响这段代码的问题。
  • 更改变量名称。如果由于任何原因发生Excel问题(变体混淆),它可以解决问题。
  • 检查项目的参考文献。如果缺少引用,VBA将无法正常工作。

在这里试过下面的代码并且工作得很好......它与你的几乎相同(除了变量名)。

Public Sub OpenExcelFiles()

    Dim vFiles As Variant
    Dim vFile As Variant
    Dim oXLFile As Excel.Workbooks

    vFiles = Application.GetOpenFilename(FileFilter:="Excel files (*.xls), *.xls", MultiSelect:=True)

    If VarType(xlsFiles) = vbBoolean Then Exit Sub

    For Each vFile In vFiles

        Set oXLFile = Workbooks.Open(vFile)

    Next vFile

End Sub