简体   繁体   中英

VBA excel if cell contains character then split text to columns

I have a fairly simple piece of code that doesn't seem to work. I need the cells to split if a word contains the character "," but only if it does. I thought that Using IF, Then, Else would work but every time it reaches a cell with no "," then i end up with "TextToColumns method of Range class failed"

If InStr(1, (Range("C32").Value), ",") > 0 Then

Range("C32").TextToColumns Destination:=Range("B14"), DataType:=xlDelimited, _
Other:=True, OtherChar:=","

Else

End If

Any help would be appreciated

Your code is ok. I've try it, and it works.

Sub Split()
If InStr(1, (Range("C2").Value), ",") > 0 Then
Range("C2").TextToColumns Destination:=Range("B3"), DataType:=xlDelimited, _
Other:=True, OtherChar:=","
Else
MsgBox "kk"
End If
End Sub

With cel without "," I get msgbox "kk" - everytime. I'm using MS 2010, maybe thats where the problem is?

You do not need a program for it. Just use Text to Columns from Data ribbon with , as data separator. If the line does not contain a comma, then the line will not be split.

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