简体   繁体   中英

Equivalent Excel Macro to C#

I have a Excel Macro that I'm trying to translate to C#, but i don't know how to translate this part:

Dim Files As Variant
Dim glos As Integer
Dim Sheet1 As Object
Dim Un As Workbook

Files = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", 2, "Open Files", , True)
If IsArray(Files) Then
    'Something with some data
    For y = LBound(Files) To UBound(Files)
        Workbooks.Open Files(y)
        b = ActiveWorkbook.Name
        glos =  glos + 1
        For Each Sheet1 In ActiveWorkbook.Sheets
            Sheet1.Copy after:= Un.Sheets(Un.Sheets.Count)
        Next
        Workbooks(b).Close False
    Next
End IF

I have tried some methods, but doesn't work, well I have this so far in C#:

var excelApp = new Excel.Application();
Excel.Workbook oWB = excelApp.Workbooks.Add(Type.Missing);

dynamic Files = oWb.Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", 2, "Select Files", Type.Missing, true);
if (Files is Array)
{
    //Something with some data
    Array ar = (Array)((object)Files);
    for(int y = ar.GetLowerBound(1); y < ar.GetUpperBound(1); y++)
    {
        oWB.Application.Workbooks.Open(ar[y]);
        b = excelApp.ActiveWorkbook.Name;
        glos += 1;
        foreach(Excel.Sheets Sheet1 in excelApp.ActiveWorkbook.Sheets)
        { 
            Sheet1.Copy(After: Un.Sheets[Un.Sheets.Count]);
        }
        ExcelApp.Workbooks[b].Close(false);
    }
}

I have been trying to improve my skills translating some macros that I use in my work to C# but I get stuck in this one, sorry for the bad english, I'm still learning the language.

Thank you in advance.

An Array is a special type of class in C# and is not the same as a VBA array. If you use Array , then you need to address an individual element like this:

ar.GetValue(y).ToString();

More information on the Array class can be found in the MSDN documentation. C# does have the concept of an array - note the non-capitalization. It is declared more like this:

string[] ar = new string[iNumberOfMembers];

And that can be addressed using ar[y]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM