Posts

Showing posts with the label Excel

Get a list of files in VBA

Image
There are two ways to get a list of files inside a folder with VBA. The first one is the Microsoft Scripting Library way, where the FileSystemObject is used. The second one is the "traditional" Dir command which returns a file each time the function is called. 'the scripting lib way Public Function GetListOfFiles(path As String, ParamArray Extensions()) As String() Dim fs As New FileSystemObject Dim fld As Folder: Set fld = fs.GetFolder(path) Dim fl As file Dim list() As String, count As Long: count = 0 For Each fl In fld.files Dim ext As String, extIncluded As Boolean, i As Long ext = fs.GetExtensionName(fl.name) extIncluded = False For i = 0 To UBound(Extensions) If LCase(ext) = LCase(Extensions(i)) Then extIncluded = True Exit For End If Next 'If ext = "xls" Or ext = "xlsb" Or ext = "xlsx" Or ext = "xlsm" Then ...

Automate Excel using C#

Image
Excel can be easily automated using C#. At first you must check that the Microsoft.Office.Interop.Excel is referenced. When the Framework 4.0 is targeted you should check that the Microsoft.CSharp.dll is referenced too. using System; using Excel = Microsoft.Office.Interop.Excel; //... Excel.Application xlApp = new Excel.Application(); //_Application xlApp = new Excel.Application(); xlApp.Visible = true; //create a workbook Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); //or open a workbook Workbook wb = xlApp.Workbooks.Open("c:\\book.xlsx"); //get the first worksheet Worksheet ws = (Worksheet)wb.Worksheets[1]; //Worksheets["Sheet1"] //create a worksheet Worksheet ws2 = (Worksheet)wb.Worksheets.Add(); //retrieve a range Range range = (Range)ws.Range["a1"]; Range range2 = (Range)ws.Cells[1, 1]; //the A1 cell range.Value="arkoudaki"; //alternative way to do the same thing //range2.set_Value(XlRangeValueDataType.xlRangeValueD...

Export modules using automation (VBA, Excel)

Image
Automation can really gives us the tools to do something very fast. The following code shows how to export all the modules in the current workbook to a destination folder. Public Sub ExportAll(targetPath as String) Dim xlApp As Excel.Application Dim xlWb As Excel.Workbook Dim VBComp As VBIDE.VBComponent ' Load workbook Set xlApp = Application 'xlApp.Visible = False Set xlWb = ActiveWorkbook 'xlApp.Workbooks.Open(sWorkbook) ' Loop through all files (components) in the workbook For Each VBComp In xlWb.VBProject.VBComponents ' Export the file If VBComp.Type = vbext_ct_StdModule Then _ VBComp.Export targetPath & VBComp.Name & ".bas" Next VBComp End Sub Two possible issues must be solved to correctly run this code. The first is to allow the code to access the VBA Object model programmatically. This can be done by correctly setting this from the Trust Center (from Excel Options). The second is to reference the Microsoft Visua...