Конвертеры vba для excel

imageПри попытке открытия файлов Excel “нашпигованных” VBS и созданных в старых версиях Excel (до Office 2007) нарвался на сообщение:

Для открытия содержащегося в этом файле проекта VBA требуется компонент, который в настоящий момент не установлен. Файл будет открыт без проекта VBA…

image

И затем появляется следующее сообщение:

Для этой книги недоступны проект VBA, элементы управления ActiveX и остальные программные средства

image

При этом механизмы VBS не работают должным образом и работать с файлом, как следствие, не представляется возможным. В моём случае проблема проявилась на терминальном сервере с Windows Server 2008 R2 EN с установленными 32-битными Office 2007 RU и Office 2010 RU.

Для решения проблемы можно воспользоваться исправлением описанным в статье KB926430 — You are requested to «search Microsoft Office Online for «VBA Converters» when you try to open or save a workbook in Excel 2007 or Excel 2010

В статье приводиться ссылка на форму заявки на скачивание хотфикса. После того вы закажете хотфикс, в почту придёт письмо с ссылкой на скачивание файла 421567_ENU_i386_zip.exe. Распаковываем этот архив и получаем файл Microsoft Office VBA Converters — Signed.EXE, который также в свою очередь распаковываем. В составе распакованных файлов внимательно читаем инструкцию в файле Readme.txt

Следуя инструкциям файла выполняем следующие манипуляции:

Для Excel 2007

На 32-битной ОС:
— Копируем файлы vbacv10.dll, vbacv10d.dll
в папку  %ProgramFiles%Common FilesMicrosoft Sharedvbavba6

ИЛИ

На 64-битной ОС с 32-битным Excel (WoW):
— Копируем файлы vbacv10.dll, vbacv10d.dll
в папку %ProgramFiles(x86)%Common FilesMicrosoft Sharedvbavba6

Для Excel 2010

На 32-битной ОС:
— Копируем файлы vbacv10.dll, vbacv10d.dll
в папку %ProgramFiles%Common FilesMicrosoft Sharedvbavba7

  • Копируем файлы xl5en32.olb, gren50.olb
    в папку где расположен файл Excel.exe%ProgramFiles%Microsoft OfficeOffice14
  • Копируем файлы vbaen32.olb, vbaend32.olb
    в системную папку Windows — %SystemRoot%System32

ИЛИ

На 64-битной ОС с 32-битным Excel (WoW):
— Копируем файлы vbacv10.dll, vbacv10d.dll
в папку %ProgramFiles(x86)%Common FilesMicrosoft Sharedvbavba7

  • Копируем файлы xl5en32.olb, gren50.olb
    в папку где расположен файл Excel.exe%ProgramFiles(x86)%Microsoft OfficeOffice14
  • Копируем файлы vbaen32.olb, vbaend32.olb
    в системную папку Windows — %SystemRoot%SysWOW64

После этого независимо от разрядности ОС с правами Администратора выполняем пакетный файл регистрации необходимых компонент — vbaconv.bat

В моём случае, как я уже отметил, в системе присутствовали каталоги как Office 2007 так и Office 2010, и поэтому я выполнил копирование и тех и других файлов, за исключением того что файлы vbaen32.olb, vbaend32.olb в моём случае уже присутствовали в системном каталоге, и поэтому я не стал их переписывать.

После этого нужные мне файлы заработали.

Microsoft Excel VBA to OpenOffice Calc Basic converter

Business Spreadsheets has developed a service to assist in the conversion
of Excel VBA code to the equivalent OpenOffice Calc Basic script. The VBA
to OO Basic converter does not completely convert Excel VBA macros to OO Basic
macros for Calc nor seamlessly migrate Excel VBA projects to OpenOffice environments.

While much of the underlying logic behind OpenOffice Basic compares to that of Visual Basic for Applications, there exists fundamental differences to the way the code is constructed. This Excel VBA to OpenOffice Basic converter offers a starting point for migrating VBA projects in Excel to the OpenOffice or Star Office Calc application. The converter may also serve as a learning mechanism to better understand the similarities and differences between the VBA and OO Basic coding specifications.

Reference should be made to the material for Porting
Excel/VBA to Calc/Star Basic at OpenOffice.org when undertaking
migrations from Microsoft Excel to OpenOffice or Star Office Calc.

The Excel VBA to OO Calc Basic Converter uses code snippet pairs of
VBA and OO Basic with place holders so that replacements can be made
using regular expressions. Users of the converter are encouraged to submit
such snippets here in a community effort to strengthen the results of
the VBA to OO Basic conversion process. A full list of current Excel
VBA to OO Basic code snippet pairs can be viewed here.

To find assistance, make suggestions or share experiences about using
this converter, please see the Help
Forum. Business Spreadsheets also offers the free Bond
Yield to Maturity Calculator in both Excel VBA and OpenOffice Basic
with open source code as an example of an Excel VBA project migrated
to OpenOffice Calc.

Submit VBA to OpenOffice Basic Code Conversion Snippets
You are encouraged to submit your own code snippets to add to the database
of VBA to OpenOffice code pairs used for the conversion process. The
conversion process executes regular expressions of the VBA code with
placeholders so that references to objects can be retained and placed
in the appropriate place of the OpenOffice Basic equivalent. To utilize
this, please
read the instructions below before submitting. All submissions will
be reviewed before inclusion.

Instructions:

Code snippets should be at the lowest level of granularity possible meaning that VBA code should be split into the smallest
components possible and still have an OpenOffice Basic equivalent.

In order to use regular expressions effectively it is best to illustrate with a existing code pair as an example.

VBA Code Pattern: Range(.*?).Offset(.*?,.*?).Value
OO Basic Format: ThisComponent.CurrentController. ActiveSheet.getCellRangeByName($1). getCellByPosition($2,$3).Value

Note that the $ signs followed by the numbers in the OO Basic Format represent the order of the .*? content in the VBA code —
i.e. $1 is will be replaced by the content of the first instance .*? in the VBA Code Pattern and so on. More detailed information on applying more complex regular expression conversions can be found here.

Current VBA to OO Basic Code Snippet Pairs:

Show >>

  • Melissa Data Quality Suite Icon

    Melissa Data Quality Suite

    Our Data Quality Suite offers global address, name, phone, and email verification all in one easy-to-use solution.

    What is Melissa Data Quality Suite? Since 1985, Melissa has combined address management and contact data quality expertise with the latest innovations to help businesses do better business through clean customer contact data.

  • Make hybrid work a reality with Robin Icon

    Whether you want to make it easier to find, book meeting rooms or search and reserve shared desks, Robin empowers office managers and employees alike to make the office work for them, and not the other way around.

  • 1

    This is an Excel based VBA script used to import bulk .VCF files that contain more than 1 Vcard and then convert them to a comma separated .CSV file or Excel xls file that can then be imported into Outlook, Google, or any other application that supports import of contacts using CSV files. This has been written to support VCF 2.0, 2.1, 3.0 and 4.0 formatted files including those with printable encoding (MIME) and has been tested with bulk VCF files from Backupify, Google Contacts (Gmail…

    Leader badge

    Downloads:
    361 This Week

    Last Update:
    2021-05-07

    See Project

  • 2

    Excel CCS

    Excel CCS

    Quick converter from Price Table to Price List in Excel

    The software Candy CCS only accepts listed items when it cames to Prices input, this file converts the supplier common Array format of prices into a List format ready to be pasted on the CCS interface. It may also be used with any other Construction Estimating Software in similar situations.
    It may also be used for any other purpose whenever a conversion from Array data to List data is needed.

    Downloads:
    1 This Week

    Last Update:
    2020-08-23

    See Project

  • 3

    Currency Converter 1.0

    CONVERT INR CURRENCY IN MANY OTHER CURRENCIES.THIS IS A APPLICATION DEVELOPED BY A 13 YEAR OLD BOY FROM INDIA.THIS APPLICATION IS BUILD IN VISUAL BASIC 6.0 . YOU CAN CONVERT THE CURRENCY IN FEW MINUTES.PLEASE VISIT THE OFFICIAL WEBSITE OF ETC (EVERYONE’S TECHNOLOGY CORP.) THAT IS etcindia.ml and OUR PRODUCT helpfox.ml

    Downloads:
    0 This Week

    Last Update:
    2017-02-18

    See Project

  • 4

    FahrenheitToCelsius allows you to convert temperature, easily and quickly on Windows PC’s without installing any software, purchasing any «apps» or receiving any crap-ware. It’s simple, easy to use and to the point, most importantly though it’s free and open source.

    Downloads:
    0 This Week

    Last Update:
    2015-06-28

    See Project

  • Unified Estimating, Operations & Business Insight Software for Heavy Construction Icon

    B2W Estimate software for heavy civil construction estimating and bidding designed to enable contractors to bid with speed, accuracy, and strategy. Users can pre-populate a centralized database with cost data and structures for labor, tasks, materials, and equipment and use these building blocks to complete bids.

  • 5

    EnergyloggerExcelConverter

    energy logger excel converter
    Converter for files of current measurement device Voltcraft Energy Logger. A excel sheet converts the .bin files into an excel spreadsheet. Energylogger 3500/4500 bin files supported(Conrad articel nbr 125323).

    Downloads:
    3 This Week

    Last Update:
    2015-08-03

    See Project

  • 6

    Catalogue of Life Converter

    The primary driver of speciation may result from hybridization instead of the accumulation of mutations. The accumulation of mutations may instead be responsible for a «maturation» which may have real physical meaning rather than being an amorphous concept.
    Scientists such as Donald Williamson and Lynn Margulis have suggested similar ideas but perhaps not going as far as this project assumes.
    This software converted the Catalogue of Life, catalogueoflife.org, into a gedcom format. It no…

    Downloads:
    0 This Week

    Last Update:
    2017-06-19

    See Project

  • 7

    Genealogy of Life

    Genealogy of Life

    Controversial ideas of Williamson, Margulis & others suggest speciation by hybridizing might be more common than originally thought.
    Taking this concept to the nth degree & assuming that indeed, speciation mostly occurs by hybridizing events, not the accumulation of mutations or genetic drift, here is a catalogueoflife2gedcom converter. It allows the tree of life to be displayed as a human genealogy tree with hybridizing events depicted as «marriages.» The idea then is that mutation accrual…

    Downloads:
    0 This Week

    Last Update:
    2017-06-19

    See Project

  • 8

    An MS Excel VBA macro converts XML to CSV. It demonstrates this capability by converting an XML-based Continuity of Care Document (CCD) into a slim Comma Separated Value (CSV) file.

    Downloads:
    20 This Week

    Last Update:
    2015-06-01

    See Project

This is somewhat a continuation on my previous post VBA – Convert XLS to XLSX in which I provided a simple little procedure to upgrade an older xls file to the newer xlsx file format.

I thought to myself, would it be nice to have a more versatile function that could migrate between various other common file formats.

So I set out to take my original function and transform it to enable to user to specify the desired output format and came up with a nice function that enabled anyone to converts Excel compatible files to another Excel compatible format.

Then I said to myself, it must be possible to do something similar for Word and set out to create a function that would enable people to convert file between the various Word compatible formats.

Below are the 2 functions I came up with.

Excel File Format Conversion Function

The following function can be used to convert files between:

  • csv -> xlsx
  • xls -> xlsx
  • xls -> xlsm
  • xls -> txt
  • xlsx -> txt
  • xlsx -> csv
  • and so on…
Enum XlFileFormat
    'Ref: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlfileformat-enumeration-excel
    xlAddIn = 18    'Microsoft Excel 97-2003 Add-In *.xla
    xlAddIn8 = 18    'Microsoft Excel 97-2003 Add-In *.xla
    xlCSV = 6    'CSV *.csv
    xlCSVMac = 22    'Macintosh CSV *.csv
    xlCSVMSDOS = 24    'MSDOS CSV *.csv
    xlCSVWindows = 23    'Windows CSV *.csv
    xlCurrentPlatformText = -4158    'Current Platform Text *.txt
    xlDBF2 = 7    'Dbase 2 format *.dbf
    xlDBF3 = 8    'Dbase 3 format *.dbf
    xlDBF4 = 11    'Dbase 4 format *.dbf
    xlDIF = 9    'Data Interchange format *.dif
    xlExcel12 = 50    'Excel Binary Workbook *.xlsb
    xlExcel2 = 16    'Excel version 2.0 (1987) *.xls
    xlExcel2FarEast = 27    'Excel version 2.0 far east (1987) *.xls
    xlExcel3 = 29    'Excel version 3.0 (1990) *.xls
    xlExcel4 = 33    'Excel version 4.0 (1992) *.xls
    xlExcel4Workbook = 35    'Excel version 4.0. Workbook format (1992) *.xlw
    xlExcel5 = 39    'Excel version 5.0 (1994) *.xls
    xlExcel7 = 39    'Excel 95 (version 7.0) *.xls
    xlExcel8 = 56    'Excel 97-2003 Workbook *.xls
    xlExcel9795 = 43    'Excel version 95 and 97 *.xls
    xlHtml = 44    'HTML format *.htm; *.html
    xlIntlAddIn = 26    'International Add-In No file extension
    xlIntlMacro = 25    'International Macro No file extension
    xlOpenDocumentSpreadsheet = 60    'OpenDocument Spreadsheet *.ods
    xlOpenXMLAddIn = 55    'Open XML Add-In *.xlam
    xlOpenXMLStrictWorkbook = 61    '(&;H3D) Strict Open XML file *.xlsx
    xlOpenXMLTemplate = 54    'Open XML Template *.xltx
    xlOpenXMLTemplateMacroEnabled = 53    'Open XML Template Macro Enabled *.xltm
    xlOpenXMLWorkbook = 51    'Open XML Workbook *.xlsx
    xlOpenXMLWorkbookMacroEnabled = 52    'Open XML Workbook Macro Enabled *.xlsm
    xlSYLK = 2    'Symbolic Link format *.slk
    xlTemplate = 17    'Excel Template format *.xlt
    xlTemplate8 = 17    ' Template 8 *.xlt
    xlTextMac = 19    'Macintosh Text *.txt
    xlTextMSDOS = 21    'MSDOS Text *.txt
    xlTextPrinter = 36    'Printer Text *.prn
    xlTextWindows = 20    'Windows Text *.txt
    xlUnicodeText = 42    'Unicode Text No file extension; *.txt
    xlWebArchive = 45    'Web Archive *.mht; *.mhtml
    xlWJ2WD1 = 14    'Japanese 1-2-3 *.wj2
    xlWJ3 = 40    'Japanese 1-2-3 *.wj3
    xlWJ3FJ3 = 41    'Japanese 1-2-3 format *.wj3
    xlWK1 = 5    'Lotus 1-2-3 format *.wk1
    xlWK1ALL = 31    'Lotus 1-2-3 format *.wk1
    xlWK1FMT = 30    'Lotus 1-2-3 format *.wk1
    xlWK3 = 15    'Lotus 1-2-3 format *.wk3
    xlWK3FM3 = 32    'Lotus 1-2-3 format *.wk3
    xlWK4 = 38    'Lotus 1-2-3 format *.wk4
    xlWKS = 4    'Lotus 1-2-3 format *.wks
    xlWorkbookDefault = 51    'Workbook default *.xlsx
    xlWorkbookNormal = -4143    'Workbook normal *.xls
    xlWorks2FarEast = 28    'Microsoft Works 2.0 far east format *.wks
    xlWQ1 = 34    'Quattro Pro format *.wq1
    xlXMLSpreadsheet = 46    'XML Spreadsheet *.xml
End Enum

'---------------------------------------------------------------------------------------
' Procedure : XLS_ConvertFileFormat
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Converts an Excel compatible file format to another format
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sOrigFile     : String - Original file path, name and extension to be converted
' lNewFileFormat: New File format to save the original file as
' bDelOrigFile  : True/False - Should the original file be deleted after the conversion
'
' Usage:
' ~~~~~~
' Convert an xls file into a txt file and delete the xls once completed
'   Call XLS_ConvertFileFormat("C:TempTest.xls", xlTextWindows)
' Convert an xls file into a xlsx file and NOT delete the xls once completed
'   Call XLS_ConvertFileFormat("C:TempTest.xls", False)
' Convert a csv file into a xlsx file and delete the xls once completed
'   Call XLS_ConvertFileFormat("C:TempTest.csv", xlWorkbookDefault, True)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2018-02-27              Initial Release
' 2         2020-12-31              Fixed typo xlDBF24 -> xlDBF4
'---------------------------------------------------------------------------------------
Function XLS_ConvertFileFormat(ByVal sOrigFile As String, _
                               Optional lNewFileFormat As XlFileFormat = xlOpenXMLWorkbook, _
                               Optional bDelOrigFile As Boolean = False) As Boolean
    '#Const EarlyBind = True 'Use Early Binding, Req. Reference Library
    #Const EarlyBind = False    'Use Late Binding
    #If EarlyBind = True Then
        'Early Binding Declarations
        Dim oExcel            As Excel.Application
        Dim oExcelWrkBk       As Excel.Workbook
    #Else
        'Late Binding Declaration/Constants
        Dim oExcel            As Object
        Dim oExcelWrkBk       As Object
    #End If
    Dim bExcelOpened          As Boolean
    Dim sOrigFileExt          As String
    Dim sNewXLSFileExt        As String

    'Determine the file extension associated with the requested file format
    'for properly renaming the output file
    Select Case lNewFileFormat
        Case xlAddIn, xlAddIn8
            sNewFileExt = ".xla"
        Case xlCSV, xlCSVMac, xlCSVMSDOS, xlCSVWindows
            sNewFileExt = ".csv"
        Case xlCurrentPlatformText, xlTextMac, xlTextMSDOS, xlTextWindows, xlUnicodeText
            sNewFileExt = ".txt"
        Case xlDBF2, xlDBF3, xlDBF4
            sNewFileExt = ".dbf"
        Case xlDIF
            sNewFileExt = ".dif"
        Case xlExcel12 = 50    'Excel Binary Workbook *.xlsb
            sNewFileExt = ".xlsb"
        Case xlExcel2, xlExcel2FarEast, xlExcel3, xlExcel4, xlExcel5, xlExcel7, _
             xlExcel8, xlExcel9795, xlWorkbookNormal
            sNewFileExt = ".xls"
        Case xlExcel4Workbook = 35    'Excel version 4.0. Workbook format (1992) *.xlw
            sNewFileExt = ".xlw"
        Case xlHtml = 44    'HTML format *.htm; *.html
            sNewFileExt = ".html"
        Case xlIntlAddIn, xlIntlMacro
            sNewFileExt = ""
        Case xlOpenDocumentSpreadsheet    'OpenDocument Spreadsheet *.ods
            sNewFileExt = ".ods"
        Case xlOpenXMLAddIn    'Open XML Add-In *.xlam
            sNewFileExt = ".xlam"
        Case xlOpenXMLStrictWorkbook, xlOpenXMLWorkbook, xlWorkbookDefault = 51
            sNewFileExt = ".xlsx"
        Case xlOpenXMLTemplate    'Open XML Template *.xltx
            sNewFileExt = ".xltx"
        Case xlOpenXMLTemplateMacroEnabled     'Open XML Template Macro Enabled *.xltm
            sNewFileExt = ".xltm"
        Case xlOpenXMLWorkbookMacroEnabled     'Open XML Workbook Macro Enabled *.xlsm
            sNewFileExt = ".xlsm"
        Case xlSYLK     'Symbolic Link format *.slk
            sNewFileExt = ".slk"
        Case xlTemplate, xlTemplate8    ' Template 8 *.xlt
            sNewFileExt = ".xlt"
        Case xlTextPrinter        'Printer Text *.prn
            sNewFileExt = ".prn"
        Case xlWebArchive         'Web Archive *.mht; *.mhtml
            sNewFileExt = ".mhtml"
        Case xlWJ2WD1        'Japanese 1-2-3 *.wj2
            sNewFileExt = ".wj2"
        Case xlWJ3, xlWJ3FJ3    'Japanese 1-2-3 format *.wj3
            sNewFileExt = ".wj3"
        Case xlWK1, xlWK1ALL, xlWK1FMT   'Lotus 1-2-3 format *.wk1
            sNewFileExt = ".wk1"
        Case xlWK3, xlWK3FM3   'Lotus 1-2-3 format *.wk3
            sNewFileExt = ".wk3"
        Case xlWK4       'Lotus 1-2-3 format *.wk4
            sNewFileExt = ".wk4"
        Case xlWKS, xlWorks2FarEast      'Lotus 1-2-3 format *.wks
            sNewFileExt = ".wks"
        Case xlWQ1       'Quattro Pro format *.wq1
            sNewFileExt = ".wq1"
        Case xlXMLSpreadsheet       'XML Spreadsheet *.xml
            sNewFileExt = ".xml"
    End Select

    'Determine the original file's extension for properly renaming the output file
    sOrigFileExt = "." & Right(sOrigFile, Len(sOrigFile) - InStrRev(sOrigFile, "."))

    'Start Excel
    On Error Resume Next
    Set oExcel = GetObject(, "Excel.Application")          'Bind to existing instance of Excel
    If Err.Number <> 0 Then          'Could not get instance of Excel, so create a new one
        Err.Clear
        On Error GoTo Error_Handler
        Set oExcel = CreateObject("Excel.Application")
    Else          'Excel was already running
        bExcelOpened = True
    End If
    On Error GoTo Error_Handler

    oExcel.ScreenUpdating = False
    oExcel.Visible = False         'Keep Excel hidden until we are done with our manipulation
    Set oExcelWrkBk = oExcel.Workbooks.Open(sOrigFile)    'Open the original file
    'Save it as the requested new file format
    oExcelWrkBk.SaveAS Replace(sOrigFile, sOrigFileExt, sNewFileExt), lNewFileFormat, , , , False
    XLS_ConvertFileFormat = True    'Report back that we managed to save the file in the new format
    oExcelWrkBk.Close False    'Close the workbook
    If bExcelOpened = False Then
        oExcel.Quit    'Quit Excel only if we started it
    Else
        oExcel.ScreenUpdating = True
        oExcel.Visible = True
    End If

    If bDelOrigFile = True Then Kill (sOrigFile)    'Delete the original file if requested

Error_Handler_Exit:
    On Error Resume Next
    Set oExcelWrkBk = Nothing
    Set oExcel = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: XLS_ConvertFileFormat" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    oExcel.ScreenUpdating = True
    oExcel.Visible = True         'Make excel visible to the user
    Resume Error_Handler_Exit
End Function

Word File Format Conversion Function

The following function can be used to convert files between:

  • doc -> docx
  • docx -> dotx
  • docx -> pdf
  • docx -> html
  • and so on…
Enum WdSaveFormat
    'Ref: https://msdn.microsoft.com/en-us/vba/word-vba/articles/wdsaveformat-enumeration-word
    wdFormatDocument = 0    'Microsoft Office Word 97 - 2003 binary file format.
    wdFormatDOSText = 4    'Microsoft DOS text format.  *.txt
    wdFormatDOSTextLineBreaks = 5    'Microsoft DOS text with line breaks preserved.  *.txt
    wdFormatEncodedText = 7    'Encoded text format.  *.txt
    wdFormatFilteredHTML = 10    'Filtered HTML format.
    wdFormatFlatXML = 19    'Open XML file format saved as a single XML file.
'    wdFormatFlatXML = 20    'Open XML file format with macros enabled saved as a single XML file.
    wdFormatFlatXMLTemplate = 21    'Open XML template format saved as a XML single file.
    wdFormatFlatXMLTemplateMacroEnabled = 22    'Open XML template format with macros enabled saved as a single XML file.
    wdFormatOpenDocumentText = 23    'OpenDocument Text format. *.odt
    wdFormatHTML = 8    'Standard HTML format. *.html
    wdFormatRTF = 6    'Rich text format (RTF). *.rtf
    wdFormatStrictOpenXMLDocument = 24    'Strict Open XML document format.
    wdFormatTemplate = 1    'Word template format.
    wdFormatText = 2    'Microsoft Windows text format. *.txt
    wdFormatTextLineBreaks = 3    'Windows text format with line breaks preserved. *.txt
    wdFormatUnicodeText = 7    'Unicode text format. *.txt
    wdFormatWebArchive = 9    'Web archive format.
    wdFormatXML = 11    'Extensible Markup Language (XML) format. *.xml
    wdFormatDocument97 = 0    'Microsoft Word 97 document format. *.doc
    wdFormatDocumentDefault = 16    'Word default document file format. For Word, this is the DOCX format. *.docx
    wdFormatPDF = 17    'PDF format. *.pdf
    wdFormatTemplate97 = 1    'Word 97 template format.
    wdFormatXMLDocument = 12    'XML document format.
    wdFormatXMLDocumentMacroEnabled = 13    'XML document format with macros enabled.
    wdFormatXMLTemplate = 14    'XML template format.
    wdFormatXMLTemplateMacroEnabled = 15    'XML template format with macros enabled.
    wdFormatXPS = 18    'XPS format. *.xps
End Enum

'---------------------------------------------------------------------------------------
' Procedure : Word_ConvertFileFormat
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Converts a Word compatible file format to another format
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sOrigFile     : String - Original file path, name and extension to be converted
' lNewFileFormat: New File format to save the original file as
' bDelOrigFile  : True/False - Should the original file be deleted after the conversion
'
' Usage:
' ~~~~~~
' Convert a doc file into a docx file but retain the original copy
'   Call Word_ConvertFileFormat("C:UsersDanielDocumentsResume.doc", wdFormatPDF)
' Convert a doc file into a docx file and delete the original doc once converted
'   Call Word_ConvertFileFormat("C:UsersDanielDocumentsResume.doc", wdFormatPDF, True)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2018-02-27              Initial Release
'---------------------------------------------------------------------------------------
Function Word_ConvertFileFormat(ByVal sOrigFile As String, _
                                Optional lNewFileFormat As WdSaveFormat = wdFormatDocumentDefault, _
                                Optional bDelOrigFile As Boolean = False) As Boolean
    '#Const EarlyBind = True 'Use Early Binding, Req. Reference Library
    #Const EarlyBind = False    'Use Late Binding
    #If EarlyBind = True Then
        'Early Binding Declarations
        Dim oWord             As Word.Application
        Dim oDoc              As Word.Document
    #Else
        'Late Binding Declaration/Constants
        Dim oWord             As Object
        Dim oDoc              As Object
    #End If
    Dim bWordOpened           As Boolean
    Dim sOrigFileExt          As String
    Dim sNewFileExt           As String

    'Determine the file extension associated with the requested file format
    'for properly renaming the output file
    Select Case lNewFileFormat
        Case wdFormatDocument
            sNewFileExt = "."
        Case wdFormatDOSText, wdFormatDOSTextLineBreaks, wdFormatEncodedText, wdFormatOpenDocumentText, wdFormatText, wdFormatTextLineBreaks, wdFormatUnicodeText
            sNewFileExt = ".txt"
        Case wdFormatFilteredHTML, wdFormatHTML
            sNewFileExt = ".html"
        Case wdFormatFlatXML, wdFormatXML, wdFormatXMLDocument
            sNewFileExt = ".xml"
        Case wdFormatFlatXMLTemplate
            sNewFileExt = "."
        Case wdFormatFlatXMLTemplateMacroEnabled
            sNewFileExt = "."
        Case wdFormatRTF
            sNewFileExt = ".rtf"
        Case wdFormatStrictOpenXMLDocument
            sNewFileExt = "."
        Case wdFormatTemplate
            sNewFileExt = "."
        Case wdFormatWebArchive
            sNewFileExt = "."
        Case wdFormatDocument97
            sNewFileExt = ".doc"
        Case wdFormatDocumentDefault
            sNewFileExt = ".docx"
        Case wdFormatPDF
            sNewFileExt = ".pdf"
        Case wdFormatTemplate97
            sNewFileExt = "."
        Case wdFormatXMLDocumentMacroEnabled
            sNewFileExt = ".docm"
        Case wdFormatXMLTemplate
            sNewFileExt = ".doct"
        Case wdFormatXMLTemplateMacroEnabled
            sNewFileExt = "."
        Case wdFormatXPS
            sNewFileExt = ".xps"
    End Select

    'Determine the original file's extension for properly renaming the output file
    sOrigFileExt = "." & Right(sOrigFile, Len(sOrigFile) - InStrRev(sOrigFile, "."))

    'Start Excel
    On Error Resume Next
    Set oWord = GetObject(, "Word.Application")            'Bind to existing instance of Word
    If Err.Number <> 0 Then            'Could not get instance of Word, so create a new one
        Err.Clear
        On Error GoTo Error_Handler
        Set oWord = CreateObject("Word.Application")
    Else            'Word was already running
        bWordOpened = True
    End If
    On Error GoTo Error_Handler

    oWord.Visible = False           'Keep Word hidden until we are done with our manipulation
    Set oDoc = oWord.Documents.Open(sOrigFile)      'Open the original file
    'Save it as the requested new file format
    oDoc.SaveAs2 Replace(sOrigFile, sOrigFileExt, sNewFileExt), lNewFileFormat
    Word_ConvertFileFormat = True      'Report back that we managed to save the file in the new format
    oDoc.Close False      'Close the document
    If bWordOpened = False Then
        oWord.Quit      'Quit Word only if we started it
    Else
        oWord.Visible = True 'Since it was already open, ensure it is visible
    End If

    If bDelOrigFile = True Then Kill (sOrigFile)      'Delete the original file if requested

Error_Handler_Exit:
    On Error Resume Next
    Set oDoc = Nothing
    Set oWord = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: XLS_ConvertFileFormat" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    oWord.Visible = True           'Make excel visible to the user
    Resume Error_Handler_Exit
End Function

Missing File Extensions

Unlike the Excel function, the Word function is currently missing some of the file extensions. I created the general framework, but could not easily find the associated file extensions to some of the file format. You need only complete the missing entry and it will work. So simply update the

sNewFileExt = "."

entries as applicable.

The Macro Converter is an add-on that makes it easier to convert Excel files
that have Visual Basic for Applications (VBA) code to Google Sheets files and
Apps Script. You can use the Macro Converter add-on to determine the
compatibility of your files and automatically convert them.

Before you begin

To use the Macro Converter:

  • You must have a Google Workspace Enterprise Plus account or a Google Workspace for Education Plus account.
  • You should have some proficiency with Excel or Google Sheets and scripting
    languages (VBA or Apps Script).
  • You should be able to read and understand basic scripts.

Install the Macro Converter add-on

  1. On your computer, go to the Macro Converter add-on on Google Workspace Marketplace.
  2. At the top right, click Install > Continue > Allow.
  3. Installation might take several seconds. Once the add-on is installed, click
    Done.

Once installed, you can find the Macro Converter add-on in Google Drive, on the right side panel. If you don’t see the side panel, at
the bottom right, click Show side panel .

How to use the Macro Converter

  1. Generate a compatibility report for the files you want to convert. See
    Determine if VBA macros are compatible with Apps Script.
  2. Update your VBA code using the information from your compatibility report.
    1. If your code is fully compatible, you might not need to make changes.
    2. If your VBA code has APIs that won’t easily convert to Apps Script code,
      the report offers workarounds in Apps Script. You can implement the Apps
      Script workarounds after you convert your files, but if you’re more
      familiar with VBA you might want to create and implement VBA workarounds
      before you convert your files.
  3. After you make changes to your VBA code, run the compatibility report again.
    This step helps confirm the increased compatibility of your files and flags
    any additional updates that should be made.
  4. Repeat steps 2 and 3 as needed. These steps maximize the compatibility of
    your files to reduce the amount of work needed after you convert them. You
    can proceed to the next step if you plan to finish applying your workarounds
    after you convert your files.
  5. Convert your files.
  6. Fix errors.
    You might need to make adjustments to your new Apps Script code to make sure
    your code works as intended.
  7. Address common issues.
    You might need to manually create items, like VBA UserForms, in Apps Script.

Related articles

  • Determine if VBA macros are compatible
  • Convert VBA macros to Apps Script
  • Fix errors in your converted code
  • Address common issues
  • Watch Macro Converter tutorials
  • List of compatible VBA APIs

Like this post? Please share to your friends:
  • Конвертеров файлов документ word
  • Конвертер файлов для документов word
  • Конвертер фото в word текст
  • Конвертер файлов pdf в word скачать бесплатно на русском
  • Конвертер формулы в excel