Question

This code snippet is working fine when the path is declared as absolute. Consider the line

var wb = xl.Workbooks.Open("C:\\temp\\temp.csv");

in the code. However, I want to declare a relative path for the same. How do I do that?

var xl = new ActiveXObject("Excel.Application");
    xl.Visible = true;
    var wb = xl.Workbooks.Open("C:\\temp\\temp.csv");
    var sheet = wb.ActiveSheet;

    wb.Worksheets.Add(after=wb.Sheets(wb.Sheets.Count));
    var pws = wb.ActiveSheet;
    pws.Name="temp_pivot";
    var pvtTable = pws.PivotTableWizard(1, varSource=wb.sheets("temp").Range("A1").CurrentRegion);
    pvtTable.PivotFields("DECISIONYEAR").Orientation = 1;
    pvtTable.PivotFields("DECISIONMONTH").Orientation = 1;
    pvtTable.PivotFields("WEEKYEAR").Orientation = 1;
    pvtTable.PivotFields("APPLICANT").Orientation = 4;
    pvtTable.PivotFields("SUM OF APPLICANT").Function=-4157;
    pvtTable.PivotFields("APPROVED").Orientation = 4;
    pvtTable.PivotFields("SUM OF APPROVED").Function=-4157;
    pvtTable.PivotFields("SOURCE").Orientation = 3;
    pvtTable.PivotFields("PRODUCTCOLOR").Orientation = 3;
    pvtTable.PivotFields("PRODUCT").Orientation = 3;
    pvtTable.PivotFields("SUB_CHANNEL_CADM").Orientation = 3;
    pvtTable.PivotFields("CHANNEL_CADM").Orientation = 3;
    pvtTable.PivotFields("MARKET").Orientation = 3;
    pvtTable.PivotFields("OFFER_TYPE").Orientation = 3;
    pvtTable.DataPivotField.Orientation=2;
    pws.Columns.Autofit;
    pws.Rows.Autofit;
    xl.DisplayAlerts =0;
    xl.DisplayAlerts = 1
    xl.CutCopyMode = 0;
    xl.EnableEvents = 0;
    xl = null;
Was it helpful?

Solution

The Windows Scripting Host part of things lets you use paths relative to the current directory, which will be the directory where you launched the script. If you launch it from the command line, then of course it'll be your current directory in the command line. If you launch it by double-clicking the file in Windows Explorer, it'll be the directory in which you double-clicked it.

You can find out what the current directory is when you launch the file in various ways like this:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var curDir = fso.GetAbsolutePathName(".");
WScript.Echo(curDir);

Excel, though, may not default to the same directory. (On my system, for instance, it defaults to the user's documents folder.) So you'll want to use fso.GetAbsolutePathName and then pass the absolute path to Excel, like this:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var xl = new ActiveXObject("Excel.Application");
xl.Visible = true;
var wb = xl.Workbooks.Open(fso.GetAbsolutePathName("temp.csv"));

That way, although you're using a relative path in your code, you're passing an absolute path to Excel so it finds it regardless of what it thinks the current directory is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top