Delete multiple columns from Excel Spreadsheet from VB.Net application?

  • Thread starter Thread starter Will
  • Start date Start date
W

Will

Can someone help with code to delete multiple columns from an excel
spreadsheet? I know which columns I need to delete. The code below will
delete a single column but I'm not sure how to delete multiple columns. I'm
tried experimenting with Dim rg As Excel.Range = xlSheet.Columns("B, D, G,
K, L") but no joy. Thanks in advance


Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

xlApp = CreateObject("Excel.Application")
xlBook = xlApp.Workbooks.Open("D:\August_Sales.xls")
xlSheet = xlBook.Worksheets(1)
Dim rg As Excel.Range = xlSheet.Columns("B")
rg.Select()
rg.Delete()
xlBook.Save()
xlApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlSheet = Nothing
xlBook = Nothing
xlApp = Nothing
 
Is there some reason that you wouldn't just repeat

Dim rg As Excel.Range = xlSheet.Columns("B")
rg.Select()
rg.Delete()

for the other columns, using the letters for those columns (working from
right to left, of course)?
 
That "could" work. The problem is that when you delete column "B", the
columns to the right are moved left. You need to be aware of that when
addressing the subsequent columns. A way arround that would be to delete
columns from right to left, as L, K, G, D, B.
 
That's why I included in the original message the comment "(working from
right to left, of course)?"
 
Back
Top