3

I have a script task which opens an excel file and saves it as a .csv but it saves the sheet that opens with the file whereas I want to choose which sheet to save as a .csv, this is the script I'm currently using:

    Public Sub Main()

    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim xl As New Microsoft.Office.Interop.Excel.ApplicationClass()
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim laPath As String = "C:\Filename.xlsx"
    xlBook = DirectCast(xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing,
    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
    oMissing, oMissing, oMissing), Workbook)

    xl.DisplayAlerts = False
    xlSheet = DirectCast(xlBook.Worksheets.Item(1), Worksheet)
    xlBook.SaveAs("C:\Filename.csv", 6, oMissing, oMissing, oMissing, oMissing,, oMissing, oMissing, oMissing, oMissing, oMissing)
    xl.Application.Workbooks.Close()
    Dts.TaskResult = ScriptResults.Success
End Sub

I think I have to use xlbook.Worksheets("Sheet1").Activate but I can't seem to find it.

Hadi
  • 36,233
  • 13
  • 65
  • 124

1 Answers1

1

You have to open worksheet by it's name and Select it using Select() function:

xlSheet = xlBook.Worksheets("Sheet1")
xlSheet.Select()

Your code will be like the following:

Public Sub Main()

    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim xl As New Microsoft.Office.Interop.Excel.ApplicationClass()
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim laPath As String = "C:\Filename.xlsx"
    xlBook = xl.Workbooks.Open(laPath)
    xl.DisplayAlerts = False
    xlSheet = xlBook.Worksheets("Sheet1")
    xlSheet.Select()
    xlBook.SaveAs("C:\Filename.csv", Excel.XlFileFormat.xlCSV,Excel.XlSaveAsAccessMode.xlNoChange)
    xl.Application.Workbooks.Close()
    Dts.TaskResult = ScriptResults.Success
End Sub 
Hadi
  • 36,233
  • 13
  • 65
  • 124
  • Thanks, select() worked although I had to use it in my format, your one gave me a runtime error.`xlSheet = DirectCast(xlBook.Worksheets("Sheet1"), Worksheet) xlSheet.Select()` – JamesBracky Mar 01 '17 at 11:26