Bat файл для запуска файла excel

Данные в формате dbf переводятся в формат xls.
Можно назвать это программированием,
но можно и просто инженерной задачей.

Случай (A) — Excel установлен и больше не хочется ничего устанавливать.
Тогда использовать либо powershell ( если Windows 7 и новее ),
либо VBScript ( В Windows XP и старее ).
Технология OLE Automation

Случай (B) — и Excel не установлен и больше не хочется ничего устанавливать,
но необходимые ODBC-драйвера w системе присутствуют.
Тогда использовать либо powershell ( если Windows 7 и новее ),
либо VBScript ( В Windows XP и старее ).
Технология ActiveX + ADO

Случай (C) — Excel не установлен, но есть желание установить доп. язык программирования
( Perl, Python, Java etc ) + соответств. модули для чтения из DBF и записи в XLS.
В этом случае даже не обязателен Windows, можно всё сделать и из под Linux.

(D) найти бесплатный dbf-to-xls converter

(E) Установить бесплатный LibreOffice/OpenOffice, если платный MS Office нежелателен
и применить схемы A или B.

итд

I designed an excel spreadsheet that takes data from a server using an RTD feed and processes it. I want the excel file to open automatically during the computers startup. The way that I have decided to go about doing this is to write a batch script that opens the excel file and to then put that batch script in the computers startup folder.

The problem I am running into relates to the batch script. The RTD feed does not work if I use the default shortcut for excel. Instead I have to use a shortcut that has the following target line:

 "C:Program Files (x86)Microsoft OfficerootOffice16EXCEL.EXE" /a "CompanyExcelAddin.CompanyFunctions"

I am able to open the file using this command line

start `"C:Program Files (x86)Microsoft OfficerootOffice16EXCEL.EXE" "C:...filename.xlsm"`

but I am not able to open a file using the following bash command

start "C:Program Files (x86)Microsoft OfficerootOffice16EXCEL.EXE" /a "CompanyExcelAddin.CompanyFunctions" "C:...filename.xlsm"

If I open it using the first batch script the RTD feed doesn’t work. If I try to run the second script the batch script doesn’t run.

How do I write a batch script that takes command line arguments for the startup program?

Проблема: мне нужно открыть документ Excel, запустить макрос, сохранить документ под отдельным именем (XXXX_YYYYMMDD), закрыть документ Excel.

Решение 1. Я думаю, что могу использовать файл.bat, чтобы открыть Excel, запустить макрос, сохранить и переименовать файл.

Вопрос решения 1: а) Я не знаю, как передать путь к файлу в качестве параметра. б) я знаю, как написать процесс на языке сценариев для.bat

Решение 2: Я думаю, что могу использовать файл.bat, чтобы открыть Excel, и создать макрос, который однажды откроется в Excel, запустит его, переименует Excel и закроет его.

Вопрос решения 1: а) Я не знаю, как передать путь к файлу в качестве параметра.

PS: Абсолютно новый с кодированием.bat

Другие предложения приветствуются

Большое спасибо за Вашу помощь

2013-01-15 15:25

3

ответа

Вы можете попробовать с гибридным файлом bat/jscript:

    rem ("open macro")/*
    @echo off
    call cscript //nologo //E:jscript excelfile.xsls
    goto :eof

    */
     var objExcel = new ActiveXObject ("Excel.Application"); 
     objExcel.Application.Run(""+WScript.Arguments.Item(0)+!mymacro"); 
    rem (){}

Если макрос внедрен в лист, вам нужно создать объект листа и получить к нему доступ.

2013-01-15 22:37

Чтобы ответить на ваш первый вопрос, вы можете передать имя файла в качестве параметра, используя

batfile.bat yourexcelfile.xls

и получить к нему доступ из командного файла, используя %1,

Тем не менее, я не знаю, как делать другие макро-вещи, но если вы узнаете, вы можете использовать это, чтобы собрать это вместе!:)

2013-01-15 16:10

Я не уверен, возможно ли это с BAt-Files, но я думаю, что сценарий powersheel мог бы сделать это…. Если это не вариант, вы можете попытаться добавить макрос в запуск файла — так что он запускается когда файл открывается…

2013-01-15 16:56

The fault must be your path isn’t actually referencing what you think it is or, an issue with the locale may be, or how it’s recognizing characters…

I just created the following

"C:Program Files (x86)Microsoft OfficeOffice14EXCEL.EXE" "C:UsersDRookDesktopa d c.xlsx"/e "C:UsersDRookDesktopMy File . dia"

It works as expected (meaning, no error message) from command prompt and a .bat file.

I suspect that the file isn’t referenced correctly some how or that your may have some locale setting which is confusing it!

To be certain (just to rule it out), find the MyFile.dia and rename it My File . dia in Explorer. Then, with the shift button held, right click your file (file.dia) and select the option Copy as path

Then paste this as the final parameter in your command.

Remember, if you didn’t create this string yourself and copied and pasted it from another source, the » marks may not do what you think they should. I suggest you re-write the entire string and then test it. Or copy my string above and test that, just rename the paths.

If D: is not a local drive, then I suggest testing with everything on your desktop (or at least, a local location where you won’t have any issues with networking or permissions).

I have even tried it with similar directory structure and it works fine.

enter image description here

Edit

I would also attempt each parameter one at a time to ensure the path is correct. So, within the command prompt type

«C:Program Files (x86)Microsoft OfficeOffice14EXCEL.EXE» and press enter

Then

«D:Desktoplibsxlam+apps+diagramViewerdiagramViewer.xlsm» and press enter

Then

«D:DesktopMyFile.dia» and press enter

Then

«D:DesktopMy File . dia» and press enter

Edit 2

Right, I can now see / understand the fault better but offer only 1 solution which is a solution you don’t want — don’t allow white space.

What is happening when I send white space in the parameter is I get the following message from Excel (note, my parameter is e/"C:UsersDRookDesktopMy File . dia")

enter image description here

Note, then problem is Excel appears to be swapping white space with the extension (so therefore see’s the white space, assumes it’s the end of a file name and creates the extension).

@Robert: Я попытался адаптировать ваш код с относительным путем и создал пакетный файл для запуска VBS.

VBS запускается и закрывается, но не запускает макрос… Любая идея о том, где проблема может быть?

Option Explicit

On Error Resume Next

ExcelMacroExample

Sub ExcelMacroExample() 

  Dim xlApp 
  Dim xlBook 

  Set xlApp = CreateObject("Excel.Application")
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  strFilePath = objFSO.GetAbsolutePathName(".") 
  Set xlBook = xlApp.Workbooks.Open(strFilePath, "ExcelsCLIENTES.xlsb") , 0, True) 
  xlApp.Run "open_form"


  Set xlBook = Nothing 
  Set xlApp = Nothing 

End Sub

Я удалил «Application.Quit», потому что мой макрос вызывает пользовательскую форму, заботясь об этом.

Приветствия

ИЗМЕНИТЬ

Я действительно отработал это, на всякий случай, когда кто-то хочет запустить пользовательскую форму «подобно» автономному приложению:

Проблемы, с которыми я столкнулся:

1 — Я не хотел использовать событие Workbook_Open, поскольку excel заблокирован только для чтения.
2 — Команда партии ограничена тем фактом, что (насколько мне известно) она не может вызвать макрос.

Сначала я написал макрос, чтобы запустить мою пользовательскую форму, скрывая приложение:

Sub open_form()
 Application.Visible = False
 frmAddClient.Show vbModeless
End Sub

Затем я создал vbs для запуска этого макроса (выполнение этого с относительным путем было сложным):

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "ExcelsCLIENTES.xlsb"
xlObj.Run "open_form"

И я, наконец, сделал пакетный файл для выполнения VBS…

@echo off
pushd %~dp0
cscript Add_Client.vbs

Обратите внимание, что в моем Userform_QueryClose:

я также включил «Установить обратно в видимый»

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    ThisWorkbook.Close SaveChanges:=True
    Application.Visible = True
    Application.Quit
End Sub

В любом случае, спасибо за вашу помощь, и я надеюсь, что это поможет, если кому-то это понадобится

Понравилась статья? Поделить с друзьями:
  • Bassotronics one word bass
  • Basic word test microsoft
  • Basic word order in english sentence
  • Basic word order examples
  • Basic word of english language