0

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

Edited by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Zinderin
0

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

0

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. :)

Edited by Zinderin: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.