C#正则表达式-使用R1C1引用从Excel公式中获取行数据

C#正则表达式-使用R1C1引用从Excel公式中获取行数据,c#,regex,excel,excel-formula,C#,Regex,Excel,Excel Formula,我正在尝试使用正则表达式获取Excel中的行引用。例如,我有一个公式: =SUM(R[-3]C[-1];R[-3]C;R[-3]C[2];R[-1]C[2]:R[1]C[3];RC[-1]) 我只需要获取数字-3,-3,-3,-1,1,0 目前,我使用的是正则表达式模式: =?(R\[[-0-9]*\]|RC) 它给了我: 但只需要获取数字就行了。此外,我必须获得0,而不是RC 提前谢谢 我无法对其进行测试,但您可以通过以下方式获得公式中引用的所有行: Range formulaCell

我正在尝试使用正则表达式获取Excel中的行引用。例如,我有一个公式:

=SUM(R[-3]C[-1];R[-3]C;R[-3]C[2];R[-1]C[2]:R[1]C[3];RC[-1])
我只需要获取数字
-3
-3
-3
-1
1
0

目前,我使用的是正则表达式模式:

=?(R\[[-0-9]*\]|RC)
它给了我:

但只需要获取数字就行了。此外,我必须获得
0
,而不是
RC


提前谢谢

我无法对其进行测试,但您可以通过以下方式获得公式中引用的所有行:

Range formulaCell = worksheet.Range("A1");
Range referencedRange = formulaCell.DirectPrecedents;

foreach(Range area in referencedRange.Areas)
    foreach(Range cell in area.Cells)
        Debug.Print((cell.Row - formulaCell.Row).ToString);    // -3, -3, -3, -1, 0, 1, 0

您非常接近-如果在正则表达式中添加另一个捕获组,则可以从
R[x]
中拉出
x
。因此,您的正则表达式将是:

=?(R\[([-0-9]*)\]\RC)

注意,这是您的正则表达式,在
[-0-9]*
周围有额外的括号

示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string formula = "=SUM(R[-3]C[-1];R[-3]C;R[-3]C[2];R[-1]C[2]:R[1]C[3];RC[-1])";
            string pattern = @"=?(R\[([-0-9]*)\]|RC)";
            System.Text.RegularExpressions.Regex parser = new System.Text.RegularExpressions.Regex(pattern);
            System.Text.RegularExpressions.MatchCollection matches;

            // parse formula
            matches = parser.Matches(formula);

            // iterate results
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                if (match.Groups[0].Value == "RC")
                {
                    Console.WriteLine("0");
                } else {
                    Console.WriteLine(match.Groups[2].Value);
                }
            }
            Console.ReadKey();

        }
    }
}

您正在使用VBA宏吗?这似乎是不可能的VBA@Slai,我正在使用C#我将捕获与
(RC?\[-?[0-9]*\])
相关的所有结果,然后在
C#
中从
R[x]
中提取所需的数字,然后从
RC[y]中获取
0
。可以通过稍微移动括号并获取每个匹配的最后一组来使用正则表达式,但请注意,
R[-1]C[2]:R[1]C[3]
引用了3行:-1、0和1。你用Interop.Excel得到公式了吗?@Slai,是的,我用的是Interop.Excel。通过分组,我可以获得数字。谢谢顺便说一下,你为我展示了一个很酷的网站