1

I am trying to select a column dynamically based on the Column headers in VBA. This is the code that I am using ,

Sub trial()

Dim colm As Long
Dim nwb As Workbook, wb As Workbook
Dim nwk As Worksheet, wk As Worksheet, wk1 As Worksheet

co1m = WorksheetFunction.Match("Header", Sheets("Sheet1").Rows(1), 0)

Columns(colm).Select

End Sub

when I try to debug it, it shows the value of 5 in colm and at the same time on the next line columns(colm).select, it shows 0 in the place of colm. Kindly help me with where I am going wrong in this. Thanks in advance

1 Answer 1

1

You have a typo in there! You have co1m and colm.

Using Option Explicit would have throw a compile error saying that co1m wasn't declared! ;)

Option Explicit

Sub trial()

Dim colm As Long
Dim nwb As Workbook, wb As Workbook
Dim nwk As Worksheet, wk As Worksheet, wk1 As Worksheet

colm = WorksheetFunction.Match("Header", Sheets("Sheet1").Rows(1), 0)

Columns(colm).Select

End Sub
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @R3uK. I am not sure its the typo that I had in the code because I looked in the code it wasn't a typo but when I added this Option Explicit, it just started working. Is there any reason behind this Option Explicit? Thanks again buddy !!
@VBA_Begineer : Option Explicit is just a best practice (you can set VBE to use it by default, check in the options) to avoid that kind of error, it'll force you to declare all the variable there is in your code, and so it'll warn you when you have a typo! ;) Please accept the answer as this solved your issue.
@R3_uK Thanks mate. I was made to wait for 10 minutes by Stack Overflow to accept your answer. Sorry for that. Thanks again !!
@VBA_Begineer : Ahaha NP, I forgot about that limitation! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.