0

I am new to VSTO and I would like to build a C# based addon that can do the same as this VBE code. I would like the same functionality of an Excel function. Any suggestions:

Function Addone(cprin As String)
    Dim INS As String

    If Len(cprin) = 9 Then
       INS = "0" & cprin
       Addone = INS
    End If
    Addone = INS

    If Len(cprin) = 10 Then
       INS = cprin
       Addone = INS
    End If
    Addone = INS

End Function
Alex Butenko
  • 3,664
  • 3
  • 35
  • 54
  • Welcome! You can format your code by putting it on a new line and adding 4 spaces at the front. That makes it easier for others to read your question. – user984003 Jan 29 '18 at 22:38
  • If you're migrating to VSTO from VBA, I would suggest using VB.NET. – aduguid Jan 30 '18 at 00:37

1 Answers1

0

For the given function, the answer is

string Addone(string cprin) {
  string INS = null;
  if (cprin.Length == 9) {
    INS = "0" + cprin;
    return INS;
  }
  if (cprin.Length == 10) {
    INS = cprin;
    return INS;
  }
  return INS;
}

Actually, it can be simplified to

string Addone(string cprin) {
  if (cprin.Length == 9) {
    return "0" + cprin;
  }
  if (cprin.Length == 10) {
    return cprin;
  }
  return null;
}

If you have a lot of code you need to translate, you can use some automatic translators, like this one (it is just an example, there are a lot of them, online and offline). It gives a good base to start. For this example, translation was like this:

private void Addone(string cprin) {
  string INS;
  if (Len(cprin) == 9) {
    INS = "0" + cprin;
    Addone = INS;
  }

  Addone = INS;
  if (Len(cprin) == 10) {
    INS = cprin;
    Addone = INS;
  }

  Addone = INS;
}

which is close to the truth, it just does not consider the fact that return statement may be different in VBA - so instead of Addone = INS you should use return INS, and fix this statement in the middle of the function. Also, instead of Len(), in C# and .net we check lenght of a string with Length property.

You can find more inspiring materials here

Alex Butenko
  • 3,664
  • 3
  • 35
  • 54