简体   繁体   中英

VB.NET excel deleting multiple columns at the same time

I am trying to delete more than one column in my excel sheet.

    For Each lvi In ListView1.Items
        If lvi.Checked = True Then
            arrayLetters = lvi.SubItems(1).Text & ":" & lvi.SubItems(1).Text & "," & arrayLetters
        End If
    Next

    arrayLetters = arrayLetters.Substring(0, arrayLetters.Length - 1)

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

The value of arrayLetters is "G:G,F:F" . For some reason that doesn't seem to work once it gets there to delete them! Only reason i am doing it this way is so that it doesn't update the table and loop to the other one. In other words, if i delete each one individually then the column moves and the letter will not be the same the next go around.

The error is on the Dim rg As Excel.Range = xlSheet.Columns(arrayLetters) line and it says:

Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

Any help would be great!

David

SOLVED

 For Each lvi In ListView1.Items
    If lvi.Checked = False Then
        arrayLetters = lvi.SubItems(2).Text & "," & arrayLetters 'Puts numbers in BACKWORDS
    End If
 Next

 arrayLetters = arrayLetters.Substring(0, arrayLetters.Length - 1)

 Dim theNumbers As String() = arrayLetters.Split(",")
 Dim num As Integer = 0

 xlApp.ScreenUpdating = False

 For Each num In theNumbers
     xlSheet.Columns(num).delete() 'Deletes columns in reverse order (7,5,4...)
 Next

Just delete the lowest numbered column N number of times to reflect how many columns in a row you want to delete. It's better to go off of column numbers rather than letters when dealing with Excel programatically. If you need a code example, let me know and I'll post one.

Edit:

Here is a code example that does what you want:

xlSheet.Columns(i).delete

You want

xlSheet.Range(arrayLetters)

I reckon, that is Range, not Column.

我认为实现的重要部分(我最初没有)是你必须使用数字作为列而不是字母。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM