none
Macro to delete multiple columns RRS feed

  • Question

  • After a join in my query, and before I run some macros, I need to delete some unneeded columns. I've tried a few ways with the example below being the most simple, but it is not working. I am trying to delete 3 columns: B, F and G.

    Sub DeleteUnneededColumns()
      Range("B:B,F:G").Delete
    
    End Sub

    The error is "Delete method of Range class failed."  It seems pretty straightforward so not sure what I'm overlooking.  It is the only worksheet in the book.

    When I write it as below, it works.  It appears that each column is renamed after the previous one deletes.  This makes the code rather ambiguous.  Is there no way to specify by name?  My column names have spaces in them and I don't think it liked that.

    Sub DeleteUnneededColumns()
      Range("B:B").Delete
       Range("E:E").Delete
       Range("E:E").Delete
    End Sub


    There are no mistakes; every result tells you something of value about what you are trying to accomplish.


    • Edited by run4it Wednesday, March 4, 2020 12:34 AM
    Wednesday, March 4, 2020 12:27 AM

All replies

  • Hi run4it,

    I tried the first code you provided, and it could work as expected.
        

    I use Excel 2016 32-bit.
        
    What is yours?

    Regards,

    Ashidacchi -- http://hokusosha.com

    Wednesday, March 4, 2020 2:40 AM
  • I use Microsoft Office Professional Plus 2019


    There are no mistakes; every result tells you something of value about what you are trying to accomplish.


    • Edited by run4it Wednesday, March 4, 2020 6:55 PM
    Wednesday, March 4, 2020 6:53 PM