VBA Question with If Else, AND

sgutknecht

New Member
Joined
Feb 4, 2015
Messages
2
This is the 1st time I have posted, so if this is a duplicate I apologize. I am new to VBA and I have the coding below. What I am trying to have happen is, if cell p5 contains "CONSOL" to name the tab one name and if does not, name it something else. I am doing something wrong as all of the results are based upon the else part of the statement. Any assistance that I could recieve would be appreciated.

Sub tabname()
Dim ws As Worksheet
For Each ws In Worksheets
On Error Resume Next
If Len(ws.Range("P5")) > 0 And ws.Range("P5") Like "CONSOL" Then
ws.Name = Mid((ws.Range("P5").Value), 12, 30)
Else:
ws.Name = Mid((ws.Range("P5").Value), 19, 30)
End If

On Error GoTo 0
If ws.Name <> Mid((ws.Range("P5").Value), 19, 30) Or Mid((ws.Range("P5").Value), 12, 30) Then
MsgBox ws.Name & " Was Not renamed, the suggested name was invalid"
End If
Next
End Sub
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
change this line of code

Code:
[COLOR=#333333]If Len(ws.Range("P5")) > 0 And ws.Range("P5") Like "CONSOL" Then[/COLOR]

to

Code:
[COLOR=#333333]If Len(ws.Range("P5")) > 0 And ws.Range("P5") Like "*CONSOL*" Then[/COLOR]

Note the wildcard asterisks
 
Upvote 0
Thank you for the assistance! I had an additional issue of having a ":" in the cell that I wanted to name the tab. I figured out how to correct that and now my macro works.
 
Upvote 0

Forum statistics

Threads
1,214,548
Messages
6,120,141
Members
448,948
Latest member
spamiki

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top