Reputation: 85
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.
Upvotes: 3
Views: 1289
Reputation: 37348
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
Upvotes: 1