2014-12-08 86 views
-1

嗨我寫了一個代碼生成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

它引發錯誤'下標超出範圍'的原因是因爲您的工作簿沒有E列指定索引的工作表。

另外請確保您不要複製工作表(「主」)。我沒有看到跳過「主要」工作表或者避免將其作爲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 
+0

是問題解決了嗎? – 2014-12-10 11:50:05