Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indentify line breaks in excel VBA

Tags:

excel

vba

I'm trying to identify a cell has line breaks(not the menu bar cell option, actual multiple lines through alt+enter), and extract each line separatedely

I have tried both

InStr(str, "\n") < 0

and

Split(str, "\n")

But doesn't seem to be working

like image 678
Mojimi Avatar asked May 30 '16 17:05

Mojimi


2 Answers

VBA is not C# ("\n"). Line breaks you'll find on: vbCr or vbLf or vbCrLf constants.

For further information, please see:
vbCr
vbLf
vbCrLf

[EDIT]

Points to Mat's Mug answer! I forgot about vbNewLine constant.

like image 92
Maciej Los Avatar answered Nov 07 '22 11:11

Maciej Los


There are no escape sequences in VBA. Use the built-in vbNewLine constant instead for the equivalent:

hasLineBreaks = InStr(str, vbNewLine) > 0

Per MSDN, vbNewline returns a Platform-specific new line character; whichever is appropriate for current platform, that is:

Chr(13) + Chr(10) [on Windows] or, on the Macintosh, Chr(13)

So you don't need to work with ASCII character codes, or even with their respective built-in constants.

Except Excel will strip CR chars from cell and shape contents, and this has nothing to do with VBA (the CR chars would be stripped all the same and "\n" wouldn't work for correctly reading that Excel data in C#, Javascript, or Python either) and everything to do with the context of where the string came from.

To read "line breaks" in a string with the CR chars stripped, you need to look for line feed chars in the string (vbLf).

But if you systematically treat the line feed character as a line ending, you'll eventually run into problems (esp.cross-platform), because ASCII 10 all by itself isn't an actual line break on either platform, and you'll find ASCII 13 characters in strings you thought you had stripped line breaks from, and they'll still properly line-break on a Mac, but not on Windows.

like image 20
Mathieu Guindon Avatar answered Nov 07 '22 10:11

Mathieu Guindon