\ is escaping ” character in lstlisting giving wrong output

The following code in VB has wrong output due to \ escaping the closing " of the string. Rest of code is then printed as if it was in a string.

Any idea how to correct that?

\documentclass{article}
\usepackage[svgnames,table]{xcolor}
\usepackage{listingsutf8}
\begin{document}
\lstset
{
   language={[Visual]Basic},
    basicstyle=\scriptsize\color{Black}\ttfamily,
    keywordstyle=\bfseries\color{Orange},
    identifierstyle=\color{Blue},
    stringstyle=\color{Red},
    commentstyle=\color{Green}
}
\begin{lstlisting}
Function filtre1(chaine As String) As String
    If Left(chaine, 1) = "\" And Not Right(chaine, 1) = "{" Then
        filtre1 = chaine + " "
    Else
        filtre1 = chaine
    End If
End Function
\end{lstlisting}
\end{document}

capture

Solutions Collecting From Web of "\ is escaping ” character in lstlisting giving wrong output"

It seems that the definition for the Basic is slightly erroneous as it includes the line

morestring=[b]"

The listings documentation is a bit tricky to follow, but it says that for a [b] type comment/string delimiters the character can be escaped using \ or by being doubled. That’s not the case for Basic: you cannot escape the " using \. So what you seem to want is

morestring=[s]""

which is a non-escapable pair of delimiters which cannot be nested.

You can alter the settings by adding the appropriate line after loading the standard Basic definition:

\documentclass{article}
\usepackage[svgnames,table]{xcolor}
\usepackage{listingsutf8}
\begin{document}
\lstset
{
   language={[Visual]Basic},
    basicstyle=\scriptsize\color{Black}\ttfamily,
    keywordstyle=\bfseries\color{Orange},
    identifierstyle=\color{Blue},
    stringstyle=\color{Red},
    commentstyle=\color{Green},
    morestring=[s]""
}
\begin{lstlisting}
Function filtre1(chaine As String) As String
    If Left(chaine, 1) = "\" And Not Right(chaine, 1) = "{" Then
        filtre1 = chaine + " "
    Else
        filtre1 = chaine
    End If
End Function
\end{lstlisting}
\end{document}