下标超出范围

时间:2014-12-08 09:21:43

标签: excel vba

您好我已经编写了生成csv文件的代码。我不断得到一个超出范围错误的下标。 请在下面找到代码。我将不胜感激这个问题的任何帮助。

注意: main中的列f由工作表的索引号组成。 main中的列e包含将存储每个文件的路径名。

Sub Gencsv()
    For i = 3 To 12
        Dim a As String
        ActiveWorkbook.Sheets("Main").Select
        a = Range("f" & i).Value
        b = Range("e" & i).Value
        Filename = b

        Application.ScreenUpdating = False
        ActiveWorkbook.Sheets(a).Visible = True
        ThisWorkbook.Sheets(a).Copy

        Filename = b
        ActiveWorkbook.SaveAs Filename, FileFormat:=xlCSV
        ActiveWindow.Close
        Sheets(a).Select
        ActiveWindow.SelectedSheets.Visible = False
        Sheets("Main").Select
        ActiveWindow.ScrollColumn = 1
        Range("c2").Select
        Application.ScreenUpdating = True
    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

它将错误'下标超出范围'是因为您的工作簿没有包含E列指定索引的工作表。

另外请确保不要复制表格(" main")。我没有看到跳过“主要'单张或避免以CSV格式复制/移动它。

以下是更正后的版本:

Sub Gencsv()
On Error GoTo x
For i = 3 To 12
    Dim a As Integer
    ActiveWorkbook.Sheets("Main").Select
    ' Get Sheet("Main") Index
    ' MsgBox "Index of Main: " & ActiveWorkbook.Sheets("Main").Index
    mainIndex = ActiveWorkbook.Sheets("Main").Index
    ' Get Sheet Index from column F
    a = Range("f" & i).Value
    ' Get CSV Filepath from column E
    b = Range("e" & i).Value

    If a = mainIndex Then
        'Do nothing if the current index is of the Sheets("Main")
    Else
        Filename = b
        Application.ScreenUpdating = False
        ActiveWorkbook.Sheets(a).Visible = True
        ThisWorkbook.Sheets(a).Copy

        Filename = b
        ActiveWorkbook.SaveAs Filename, FileFormat:=xlCSV
        ActiveWindow.Close savechanges:=True
        ThisWorkbook.Activate
        Sheets(a).Select
        ActiveWindow.SelectedSheets.Visible = False
        Sheets("Main").Select
        ActiveWindow.ScrollColumn = 1
        Range("c2").Select
        Application.ScreenUpdating = True
    End If

Next i
x:
MsgBox "[ERROR] Sheet with index: " & a & " does not exist!"
End Sub