简体   繁体   中英

Excel VBA Column Range selection selecting wrong columns

I'm working on a macro that will run on multiple worksheets in one Workbook, switching between sheets and copying/pasting data to one master sheet.

My issue is that when I switch to another sheet using Windows(index).Activate and then try to select some columns to delete, it doesn't select the columns correctly. I'm using the code below, and the EXACT same code works just fine in the master sheet, but as soon as I switch to another sheet in the VBA code and use it, it selects all columns starting with column 1 to the end of the data.

The idea behind the code below is to start at Column 1 and search for the column called "Composite Rating". I then want to DELETE all columns starting at column 3 up to the Composite Rating column.

Can someone tell me what I'm doing wrong? Thank you very much for any help!

For counter = 1 To 40 Step 1
        Cells("1", counter).Select
        strval = ActiveCell.Value
    If strval = "Composite Rating" And counter <> 3 Then
        Range(Cells(1, 3), Cells(1, counter - 1)).EntireColumn.Select
        Selection.Delete Shift:=xlLeft
        Exit For
    End If
    Next counter

EDIT: Sorry, should have mentioned my setup. I am using Excel 2007 on Windows 7. I've tried on both xls and xlsx files, same result.

Try below code :

 Dim rng As Range
    Set rng = Range("A1:Z1").Find("Composite Rating")

    If Not rng Is Nothing Then
        If rng.Column > 3 Then
            Range("C1", rng).EntireColumn.Delete
        End If
    End If

The index property in the Windows collection changes when selecting other windows -> it's relative!

Use the Workbooks collection instead.

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