Hi im new to c#.. just wondering how to convert this vba code:-

Sub AddUP()
x = 1
For i = 2 To 100
x = x + i
Next i
ActiveCell.Value = x
End Sub

Best Regards

There's a pretty good online conversion tool in Developer Fusion website. You can convert from VB.NET or C# to VB.NET, C#, Python and Ruby. And you can try to convert VB6 and VBA code too.

So here's the conversion (I added type definitions for variables)

public void  AddUP()
{
  int x;
  x = 1;
  for (int i = 2; i <= 100; i++) {
    x = x + i;
    }
 ActiveCell.Value = x;
}

The code doesn't make sense because the loop results always 5050 which is assigned to ActiveCell. Anyway, all you have to add now is reference to Excel component and declare ActiveCell.

HTH

Hi im new to c#.. just wondering how to convert this vba code:-

Sub AddUP()
x = 1
For i = 2 To 100
x = x + i
Next i
ActiveCell.Value = x
End Sub

Best Regards

Here is how I got it to work (learning for myself) ... but I went with a WHILE loop to make it more flexible. And I defined the values separately so they could be defined on the fly, or the code could be integrated into a method that received starting and max values.

Prep ... I dropped a DataGridView on the form and created and gave it one column. I did not define any rows.

Then I created a button, and dropped this code into the Click event:

private void button1_Click(object sender, EventArgs e)
        {
            // Starting value
            Int32 x=2;

            // Maximum value
            Int32 z = 100;

            // Current Cell index
            Int32 cell = 0;

            // Make sure we can write to the cells...
            dataGridView1.ReadOnly = false;

            while(x <= z)
            {
                dataGridView1.Rows.Add();
                dataGridView1[0,cell].Value = x.ToString();
                x++;
                cell++;
            }

            // Set the active cell to the first one...
            dataGridView1.CurrentCell = dataGridView1[0,0];
        }

Please mark this as solved if it answered your question. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.