Passing a parameter to an Excel file when opening it

I would like to know if it is possible to pass a parameter to an Excel file when calling that file from within another Excel file using VBA. I am using the 2007 version. An example of what I would like to do is what we use to do with DOS programs and command
line parameters. I would like to have the Excel file I just opened do something depending on the parameter passed to it and then close.
Might be an easy question but I'm stumped. Any ideas?

Step.1 Create a macro-enabled workbook
Step.2 Open the workbook, and open the VBA, insert a moudle, copy and paste the following code sample in the module
Option Base 0
Option Explicit
Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long)
Function CmdToSTr(Cmd As Long) As String
Dim Buffer() As Byte
Dim StrLen As Long
If Cmd Then
StrLen = lstrlenW(Cmd) * 2
If StrLen Then
ReDim Buffer(0 To (StrLen - 1)) As Byte
CopyMemory Buffer(0), ByVal Cmd, StrLen
CmdToSTr = Buffer
End If
End If
End Function
Step.4 Copy and paste the following code sample into ThisWorkbook
Private Sub Workbook_Open()
Dim CmdRaw As Long
Dim CmdLine As String
Dim myParam As String
CmdRaw = GetCommandLine
CmdLine = CmdToSTr(CmdRaw)
myParam = Right(CmdLine, 6)
MsgBox myParam
End Sub
Step.4 Sign your code or modify the macro security settings to allow the macro to run automatically
Step.5 Save and close the workbook
Step.6 Run command line with the parameter, for example:
Excel "Server\ShareFolder\TheWorkbook.xlsm" /e/myParam
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The code sample above will pass the last 6 characters (modify the code if you need more or less) to the workbook
The workbook will display a message box to display the parameter we passed from the command line, add the other function as you need
The code sample refers to the reply from Air_Cooled_Nut in
http://www.vbforums.com/showthread.php?366559-Excel-How-to-Pass-Command-Line-Parameter-DKenny-is-KING!
Max Meng
TechNet Community Support
A new Office has arrived, try it now.
A beautiful Start. It begins here. Windows 8 and Windows RT.
Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Similar Messages

  • What parameters should i pass inorder to upload an excel file in gui_upload

    what parameters should i pass inorder to upload an excel file in gui_upload
    Thanks in advance.
    Ahmed.

    check below program....
    *& Report  UPLOAD_EXCEL                                                *
    *& Upload and excel file into an internal table using the following    *
    *& function module: ALSM_EXCEL_TO_INTERNAL_TABLE                       *
    REPORT  UPLOAD_EXCEL no standard page heading.
    *Data Declaration
    data: itab like alsmex_tabline occurs 0 with header line.
    Has the following format:
                Row number   | Colum Number   |   Value
         i.e.     1                 1             Name1
                  2                 1             Joe
    TYPES: Begin of t_record,
        name1 like itab-value,
        name2 like itab-value,
        age   like itab-value,
        End of t_record.
    DATA: it_record type standard table of t_record initial size 0,
          wa_record type t_record.
    DATA: gd_currentrow type i.
    *Selection Screen Declaration
    PARAMETER p_infile like rlgrap-filename.
    *START OF SELECTION
    call function 'ALSM_EXCEL_TO_INTERNAL_TABLE'
           exporting
                filename                = p_infile
                i_begin_col             = '1'
                i_begin_row             = '2'  "Do not require headings
                i_end_col               = '14'
                i_end_row               = '31'
           tables
                intern                  = itab
           exceptions
                inconsistent_parameters = 1
                upload_ole              = 2
                others                  = 3.
      if sy-subrc <> 0.
        message e010(zz) with text-001. "Problem uploading Excel Spreadsheet
      endif.
    Sort table by rows and colums
      sort itab by row col.
    Get first row retrieved
      read table itab index 1.
    Set first row retrieved to current row
      gd_currentrow = itab-row.
      loop at itab.
      Reset values for next row
        if itab-row ne gd_currentrow.
          append wa_record to it_record.
          clear wa_record.
          gd_currentrow = itab-row.
        endif.
        case itab-col.
          when '0001'.                              "First name
            wa_record-name1 = itab-value.
          when '0002'.                              "Surname
            wa_record-name2 = itab-value.
          when '0003'.                              "Age
            wa_record-age   = itab-value.
        endcase.
      endloop.
      append wa_record to it_record.
    *!! Excel data is now contained within the internal table IT_RECORD
    Display report data for illustration purposes
      loop at it_record into wa_record.
        write:/     sy-vline,
               (10) wa_record-name1, sy-vline,
               (10) wa_record-name2, sy-vline,
               (10) wa_record-age, sy-vline.
      endloop.

  • How do I save a PDF as an excel file when the PDF is horizontal. Adobe tries to rotate the page, but the data is entered in an  horizontal format.

    How do I save a PDF as an excel file when the PDF is horizontal. Adobe tries to rotate the page, but the data is entered in an  horizontal format.

    Thanks for the quick reply.  I figured out how to get the desired results by using tagging.  For anyone who may reference this post in the future, I went to "Customize" in the top right corner of Adobe, then selected "Create new tool set...", looked under "accessiblity and found the "tag" option.  Hit ok, tag is added to the toolbar.  Then I highlighted the dataset in the PDF that was relevant to the output format, then clicked "tag", saved as spreadsheet.  Sorry I can't provide more details on how tagging works or if there's a more elegant solution available, but I'm sure one's out there.

  • Unable to write data into excel file when it's close

    Hi,
    I'm facing this problem and it's a bit weird. I'm using the following method to insert data into excel file. But when excel file is close, it unable to write data into the excel sheet. But it was able to write the data into the excel sheet if i open the excel file when running the program.
    Can anyone please tell me what's wrong to the code?
    public int updateLog(String sheet, String no, String cpId, String CatId, String rbtCode, String rbt, String rbtName, String artistName, String price, String rbtFileName, String songId, String msg){
            int result = -1;
            try{
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
                String actionDate = formatter.format(new Date());
                rbtName = rbtName.replaceAll("'", "''");
                artistName = artistName.replaceAll("'", "");
                String sql = "insert into [Sheet3$] (Code, CpID, CategoryID, RBTCode, RBT, RBTName, ArtistName, Price, RBTFileName, SongID, UploadStatus, FileUploadedDateTime) ";
                sql = sql + " values ('" + no + "', '" + cpId + "', '" + CatId + "', '" + rbtCode + "', '" + rbt + "', '" + rbtName + "', '" + artistName + "', '" + price + "', '" + rbtFileName + "', '" + songId + "', '" + msg + "', '" + actionDate + "')";
                System.out.println(sql);
                log.writeLog(sql);
                result = stmnt.executeUpdate(sql);
            } catch(Exception e){
                e.printStackTrace();
                log.printStackTrace(e);
            return result;
        public int openConnection(){
            int result = -1;
            try{
                Class.forName(dbDriver);
                c = DriverManager.getConnection(conStr + excelFilePath+";ReadOnly=0;");
                stmnt = c.createStatement();
            } catch(Exception e){
                e.printStackTrace();
                log.printStackTrace(e);
                return -1;
            return 1;
        }Thanks

    HI,
    i hv a doubt regarding reading / opening of a
    password protected Excel file using jxl( java ) .
    How to read / open a password protected Excel file
    thro Java (jxl ) program .plz let me know some
    example also .
    Regards,
    Ramesh P
    845935822cross posting !! answered here
    http://forum.java.sun.com/thread.jspa?threadID=710466&messageID=9507085#9507085

  • Format excel file when it is downloaded

    How to format excel file when it downloaded from SAP table

    Hi,
    In my opinion this would not be straight forward . Actully there are two possibilities :
    1. Create a dynamic itab with the structure as you desire in your requirement. But is it possible to have a itab where each row has a different structure. ? experts pls comment on this. ( extract & field group concepts are used to acheive the different structures for each line ).
    2. The more possible way i feel is to use the OLE excel concepts. Here we can add data to the excel sheet as wanted by you. Pls check for a beginners article by Rehan Zaidi ( SAP tips ).
    In this case you can keep on adding values to the excel ( may be in a loop over your data table ) . For ex : you can add the title Annual Price Book for Program - B4, then the customer & date data & finally the material data. This needs to be repeated again for the next Sales order.
    Regards,
    Sharat.

  • All excel files keep opening when I open excel?

    All excel files keep opening when I open excel. I can't quit excel or Force Quit until the files stop opening.

    Dealing With The Resume Feature of Lion
    Managing Mac OS X Lion's application resume feature.
    If you shutdown your computer you should get a dialog asking if you want applications to resume on the next startup. Simply uncheck the box to prevent that from occurring. Open General preferences and uncheck the option to Restore windows when quitting and re-opening apps. You can also install a third-party utility to control resume features on individual applications: RestoreMeNot or Application State Cleaner.
    It is possible to completely stop the Resume feature although I'm unconvinced that it is that annoying. Nevertheless see the following:
    If you have not yet done so you must first make your /Home/Library/ folder visible. Open the Terminal application in the Utilities folder. At the prompt paste the following command line:
    chflags nohidden ~/Library
    Press RETURN. Quit the Terminal application.
    In the Finder navigate to the /Home/Library/Saved Application State/ folder. Delete the contents of the folder. Back up to the /Home/Library/ folder. Select the Saved Application State folder. Press COMMAND-I to open the Get Info window. In the Sharing and Permissions panel at the bottom click on the lock icon and authenticate. Set each of the listed entries to Read Only. Close the Get Info window.
    Quit all open programs except the Finder (this is very important.) Next, navigate to the /Home/Library/Preferences/ByHost/ folder. Look for a .plist file with "com.apple.loginwindow." in the file name followed by some numbers in hexadecimal. Select the file. Press COMMAND-I to open the Get Info window and in the Sharing and Permissions panel click on the lock icon and authenticate. Set each of the listed entries to Read Only. Close the Get Info window. If you also find a file with the same filename but with a last extension of ".lockfile," then you should delete it.
    The above should eliminate the Resume feature system-wide. Note that any future system updates or upgrades will likely undo these changes. You will then need to repeat this procedure assuming there are no major changes in OS X related to it.

  • Stop Excel changing a file when opened

    Is there a way to stop Excel (and possibly Word too) changing the Excel file when you open it, and then close it without saving. 
    Excel updates the last opened date, and does not change the update date. Like this: http://spreadsheetpage.com/index.php/oddity/who_last_opened_that_file/
    I do not want this to occur as I have a sync'ing system which creates unessisary noise, and it also causes sync issues and merge conflicts for changes that are not changes. 
    Can you turn it off?

    Hello ,
    Thank you for your question.
    I am trying to involve someone familiar with this topic to further look at this issue.
    Thanks
    George Zhao
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please click "[email protected]"

  • Can't save 24 x 36 ai version 9 file when opened in CS6

    Can’t save 24 x 36 ai version 9 file when opened in CS6, even when opened as an outline format. I was able to save the file when reduced to 8 x 11, once saved I  resized it back to 24 x 36 but it still didn’t work. Any help would be greatly appreciated thanks

    Sorry to have taken up your time, I have figured it out.  I have about 50 layers and one was bad, process of elimination, I deleted one by one till I found the layer that was causing it to fail.  Files I had converted from .DWG to AI coused an error

  • VB Script That Detects if A Specific Excel File is Open

    Hi Guys,
    I'm trying to move away from Task Scheduler as my trigger for opening an Excel file. The problem there is it has a minimum of 5 min interval (I need at least 30 sec) and If the process of the initial instance of the Excel file is longer than the usual that
    after 5 min another instance executes it messes up my memory bandwidth. What I want is to use VB Script that first check if a particular Excel file is open if yes then wait for another 30 sec to check.
    Question: What is the right syntax/code for detecting a specific Excel file and loops every 30 sec. But I also want to be able to end the loop if I want to.
    Here is my current code:
    Gateway Timeout
    RequestURI=http://timeentry/
    Set Recordset = CreateObject("ADODB.Recordset")
    ConnString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=PHMNWWKS027604; DATABASE=db_skusetup; " &_
    "UID=root;PASSWORD=; OPTION=3"
    'Check for Export Query'
    Recordset.ActiveConnection = ConnString
    exportSQL = "SELECT * FROM tb_queue_export WHERE request_status = 'Pending' ORDER BY request_id DESC LIMIT 1"
    Recordset.Open exportSQL
    Set objExcelExtract = CreateObject("Excel.Application")
    Set objWorkbookExtract = objExcelExtract.Workbooks.Open("C:\Users\ushuam00\Desktop\LAPTOP.xlsx")
    If objWorkbookExtract.ReadOnly then
    if Recordset.Fields(3) <> "" then
    end if
    end if
    test= MsgBox(Recordset.Fields(3),3,Recordset.EOF)
    Recordset.Close
    ReadOnly is not doing it for me. 

    The only way to test it is to open it. Just open writable and, if the file is open you open with fail  then loop and try again until you can open it.  Once open just execute your macro.
    This can loop until you can open the file.
    Set xl = CreateObject("Excel.Application")
    Do While True
    Set wb = xl.WorkBooks.Open("C:\scripts\test.xlsx")
    If wb.ReadOnly Then
    MsgBox "readonly"
    wb.Close()
    Else
    MsgBox "OK"
    Exit Do
    End If
    WScript.Sleep 5000
    Loop
    xl.Quit
    ¯\_(ツ)_/¯

  • Any solutions for lost render/preview files when opening files?s

    Have any solutions been found for the intermittent lost render/preview files when opening a large file? I have Premiere CS6. A large project file that I have been working on lately opened without a hitch with previews intact ...until I bought new faster hard drives and rebuilt the computer (built with the same drive letters). I just installed the latest updates. When I now open this file, a segment of the sequence always opens without previews, unrendered, no matter how many times I rendered the file previously. I don't use 3rd party plugins. I am using the warp stabilizer. I tried all the suggestions that I have found on the forums (using a blank sequence to close and open, unchecking “write XMD…” etc.) but none work. I checked the render/preview drive, and these files are on that drive but they will no longer link to the project. It now takes a good 15 minutes to re-render every time I open.

    I may have found a solution. I took out the warp stabilizer, and then added it back in on the clips in question, and then re-analysed and re-rendered. So far, so good. It seems that bringing in the warp stabilizer effect in the file into the re-built computer needed re-analysing (as I do after this 2 day exercise.)

  • How can i print an Excel file when in the full screen mode (no print options on toolbar or right clk

    using Vista, sometimes after creating and saving an excel file, the document is not visible when the file is reopened.
    selecting full screen mode makes the document visible, but the toolbars disappear and the print option does not show up on a right click.  How can i print the document and see the document in some other mode than full screen?

    In order to print, you can click the CTRL+P keys to launch the print dialog,
    Regarding the missing toolbar, try clicking the ALT key to shouw the software menu, then look around under the view option for any available toolbar settings,
    If you cannot find it, i would recommend you to try the Microsoft support forums, as they have some more knowledge with their software features
    Say thanks by clicking the Kudos thumb up in the post.
    If my post resolve your problem please mark it as an Accepted Solution

  • Why does Apple say that Numbers can open and save Excel files, when in actuality, it can only open .XLSX files and only Export to Excel (not save-as excel)?

    When attempting to open .XLS files in Numbers, the format is not recognized. When the format is .XLSX, the format is recognized. Why is it this way? It's still much more common for folks to have the .XLS file format on their excel files. Why would Numbers not be backwards-compatible?
    Additionally, to state in the benefits of this program that one can save to 'Excel' is a little misleading. You can't save to anything except .numbers. Sure, you can export to Excel (with file extension .XLS, I might add), but you can't save or save-as.
    Does anyone else see the irony in being able to export to .XLS but not be able to open an .XLS?
    There is something to be said for clarity.
    You can't expect folks to have Numbers and Excel on their systems, so how else are they supposed to open .XLS files in Numbers?
    And I don't need to see another advertisement for NeoOffice or OpenOffice here, thanks. I'd actually like Numbers to be a little more sensible.
    That is all.

    When the advertisements were written, there was no Lion so we were able to Save As Excel.
    At thiqs time there is no longer Save As command under Lion but the feature is always available.
    When your editing task is ended, you are free to use this scheme:
    File > Duplicate
    File > Save and in the dialog you will have the option save as Excel.
    Numbers isn't and I hope that it will not become an Excel editor.
    Its resources contain a flag defining it this way.
    I posted several times a script editing this resource.
    This morning I'm not in a mood allowing me to do your duty.
    Search by yourself in existing threads with a keystring like
    viewer AND editor
    Yvan KOENIG (VALLAURIS, France) jeudi 27 octobre 2011 09:40:23
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.2
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community

  • How to get Formatted Excel file when downloading spool request of a r paint

    I have scheduled a Report painter program  in background  & spool is generated .
    When I download the output in the Excel file its not in the proper format . We need to format the file file by adding  deleting blank Line in the report .
    Can it be possible when we Download the Report painter. Its come The generated Excel file should come in formatted way.
    Thanks

    kiro123 wrote:
    I have scheduled a Report painter program  in background  & spool is generated .
    >
    > When I download the output in the Excel file its not in the proper format . We need to format the file file by adding  deleting blank Line in the report .
    >
    > Can it be possible when we Download the Report painter. Its come The generated Excel file should come in formatted way.
    >
    >
    > Thanks
    Yes the report painter report especially in the hierarchial format will not make much sense when you download to excel. Until now I also have not seen any solution to this.

  • Excel automatically create .tmp file when open after close Excel, tmp file still there

    Anytime I save a change to one of my Excel files, the TMP file appears in the destination folder and remains.  The "main" Excel file
    saves the retains the changes that I made and after each subsequent change, a new TMP file is created...old TMP files are not deleted.  This is only happening with Excel files.

    Hi,
    From your description, I understand that  you want .tmp file disappear . If there is any misunderstanding, please feel free to let me know.
    This issue can be related to many factors.
    First,  try to check out file->save-> Save autorecover information, if you use Excel 2010.
    If the problem persists, it may be a permissions problem.
    Take ownership of the related file
    =============
    1.      In the "Start" menu, locate "Command Prompt". Right-click and choose "Run as Administrator".
    Note:  If you are prompted for an administrator password or confirmation, type the password or provide confirmation.
    Note 2: In Windows XP, click Start >Run, type cmd and press Enter.
    2.      Type the following commands, then press "Enter" to execute them one by one. Please note the space before the command and its parameter.
    takeown /f  <path>\<file name>
     cacls <path>\<file name> /G administrators:F
    3.      Restart the computer to check the issue.
    More references:
    http://support.microsoft.com/kb/308421
    If all user has full control rights , the .tmp file still in the folder ,please clean the virus .
    You could try disabling this program to see if the problem goes away.
    Please take your time to try the suggestions and let me know the results at your earliest convenience. If anything is unclear or if there is anything I can do for you, please feel free to let me know.

  • Maintaing the formulas from an existing excel file when creating a pdf form

    Im sure its been asked but I would like to maintain the active formulas in my existing excel (2013) file when I create a new form utilizind Adobe Acrobat XI Pro.
    Thanks,

    Not possible.  You have to re-create them.

Maybe you are looking for

  • BT Infinity Connection Issue (On Going)

    Hi, i've been having problems with my connection over the past 2 weeks and since it seems that none of the people i talk to have any idea what's going on, i thought that i would post my issue on here and see if any one can help. I will try to keep th

  • Problem in Graphic Driver AMD Radeon HD 7670M

    Hi Guys , i'm new Here ,i had Hp Pavilion G6 2332se ,it has AMD Radeon HD 7670M ,i tried to update it but this was the result please help me ,how to solve this problem ?

  • Delete automatically Workitem from the INBOX

    Is it possible to remove or delete workitem from the inbox of the remaining agents, when the workitem is sent to multiple agents at a time, and one of the agent completes the workitem ? Can anyone help me for this problem ?

  • How to download Flash Player 11.8.800?

    it says: Please note, depending on your settings, you may have to temporarily disable your antivirus software.

  • Run as dialog box, is this normal?

    I have run several seaches in the forum and google and can not seem to find or phrase my question correctly. Dialog box says "run as. which user account do you want to use to run this program." I have a dell, that has multiple user accounts, the acco