Prevent null reference exception when expression contains a single quoted worksheet name with an embedded ! character. Previously the single quotes were removed and the code simply split on the ! because it assumed the ! separated the worksheet name from the address. In the case of a worksheet name with an embedded !, the split erroneously occurred on the ! within the worksheet name. We then got a null reference exception because the worksheet name was invalid and could not be found.
diff --git a/EPPlus/ExcelAddress.cs b/EPPlus/ExcelAddress.cs index c4c8c37..70f3012 100644 --- a/EPPlus/ExcelAddress.cs +++ b/EPPlus/ExcelAddress.cs
@@ -264,14 +264,7 @@ address = address.Trim(); if (address.StartsWith("'")) { - int pos = address.IndexOf("'", 1); - while (pos < address.Length && address[pos + 1] == '\'') - { - pos = address.IndexOf("'", pos+2); - } - var wbws = address.Substring(1,pos-1).Replace("''","'"); - SetWbWs(wbws); - _address = address.Substring(pos + 2); + SetWbWs(address); } else if (address.StartsWith("[")) //Remove any external reference { @@ -306,23 +299,51 @@ } private void SetWbWs(string address) { - int pos; - if (address[0] == '[') + int pos = 0; + + // Get Workbook, if any + if (address[pos] == '[') { pos = address.IndexOf("]"); - _wb = address.Substring(1, pos - 1); - _ws = address.Substring(pos + 1); + _wb = address.Substring(1, pos - 1); + pos++; } else { _wb = ""; - _ws = address; } - pos = _ws.IndexOf("!"); + + // Get Worksheet + if (address[pos] == '\'') + { + int startPos = pos; + pos = address.IndexOf("'", pos + 1); + while (pos < address.Length && address[pos + 1] == '\'') + { + pos = address.IndexOf("'", pos + 2); + } + _ws = address.Substring(startPos + 1, pos - startPos - 1).Replace("''", "'"); + pos++; + } + else + { + int startPos = pos; + pos = address.IndexOf("!", pos); + if (pos > -1) + { + _ws = address.Substring(startPos, pos - startPos); + } + } + + // Get Address + pos = address.IndexOf("!", pos); if (pos > -1) { - _address = _ws.Substring(pos + 1); - _ws = _ws.Substring(0, pos); + _address = address.Substring(pos + 1); + } + else + { + _address = ""; } } internal void ChangeWorksheet(string wsName, string newWs)