VBS Reopen already open Excel file - excel

I'm a newbie with vbs and trying to figure out how to reopen excel file.
I have like 100+ excels in one folder, where I need to open them one by one and run the macro.
It is working pretty well except for files, which are already open. I would like to reopen them and edit them.
Could you please advise how to do it?
Bellow is the code:
Const sRootFolder = "C:\test"
Dim oFSO, oFile ' File and Folder variables
Dim xlApp, xlBook, objWorkbook
Start
Sub Start()
Initialize
ProcessFilesInFolder sRootFolder
Finish
End Sub
Sub ProcessFilesInFolder(sFolder)
' Process the files in this folder
For Each oFile In oFSO.GetFolder(sFolder).Files
If IsExcelFile(oFile) Then ProcessExcelFile oFile.Path
Next
End Sub
Sub Initialize()
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set xlApp = CreateObject("Excel.Application")
End Sub
Sub Finish()
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Set oFSO = Nothing
End Sub
Function IsExcelFile(oFile)
IsExcelFile = (InStr(1, oFSO.GetExtensionName(oFile), "xls", vbTextCompare) > 0) And (Left(oFile.Name, 1) <> "~")
End Function
Sub ProcessExcelFile(sFileName)
Set xlBook = xlApp.Workbooks.Open(sFileName, 0, True)
Set objWorkbook = xlApp.Workbooks.Open(sFileName)
xlApp.Run "macro"
End Sub
Sub Save()
xlBook.Save
xlBook.Close
xlApp.Quit
WScript.Echo "Finished."
End Sub

Related

convert all xlsx files in directory to text

I am trying to create a button in a .xlsm that will convert each of the ~100 .xlsx files in the myFolder directory to .txt. The below VBA code returns an Expected End Suberror. The data is always in `Sheet 1" even though there may be other sheets present.
The Dos command executes and converts the files but they are unreadable (something to do with excels formatting?). I am not sure what to do? Thank you :)
Dos
cd C:\Users\Desktop\folder
Copy *.xlsx *.txt
VBA
Option Explicit
Private Sub CommandButton1_Click()
Dim oFSO, myFolder
Dim xlText
myFolder = "C:\Users\Desktop\folder"
Set oFSO = CreateObject("Scripting.FileSystemObject")
xlText = -4158 'Excel txt format enum
Call ConvertAllExcelFiles(myFolder)
Set oFSO = Nothing
Call MsgBox("Done!")
Sub ConvertAllExcelFiles(ByVal oFolder)
Dim targetF, oFileList, oFile
Dim oExcel, oWB, oWSH
Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
Set targetF = oFSO.GetFolder(oFolder)
Set oFileList = targetF.Files
For Each oFile In oFileList
If (Right(oFile.Name, 4) = "xlsx") Then
Set oWB = oExcel.Workbooks.Open(oFile.Path)
For Each oWSH In oWB.Sheets
Call oWSH.SaveAs(oFile.Path & ".txt", FileFormat:=xlTextWindows)
Next
Set oWSH = Nothing
Call oWB.Close
Set oWB = Nothing
End If
Next
Call oExcel.Quit
Set oExcel = Nothing
End Sub
The first lines of your code belong in Private Sub CommandButton1_Click()
(it has to be closed by End Sub)
Option Explicit and proper code indentation can help in this situation
Try this version:
Option Explicit
Private Sub CommandButton1_Click()
Dim myFolder As String
myFolder = "C:\Users\Desktop\folder"
ConvertAllExcelFiles myFolder
MsgBox "Done!"
End Sub
Public Sub ConvertAllExcelFiles(ByVal folderPath As String)
Dim xlApp As Object, wb As Workbook, ws As Variant, fso As Object
Dim fileList As Object, itm As Object, fileName As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileList = fso.GetFolder(folderPath).Files
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
For Each itm In fileList
If Right(itm.Name, 4) = "xlsx" Then
Set wb = xlApp.Workbooks.Open(itm.Path)
fileName = fso.GetParentFolderName(itm.Path) & "\" & fso.GetBaseName(itm.Path)
If True Then 'if converting all sheets use For loop (Change True to False)
wb.Sheets(1).SaveAs fileName & ".txt", FileFormat:=xlTextWindows
Else
For Each ws In wb.Sheets
ws.SaveAs fileName & " - " & ws.Name & ".txt", FileFormat:=xlTextWindows
Next
Set ws = Nothing
End If
wb.Close: Set wb = Nothing
End If
Next
xlApp.Quit
End Sub

Excel macro loop using VBS

I would like to run a VBA macro named MyMacro, which is saved as MyMacro.bas for many excel files. I have the VBS code below, but it is not doing what I want. I would really appreciate if somebody could take a look at it.
I am using Excel 2013. The files are saved as .xls.
Thank you.
Const sRootFolder = "C:\Documents"
Const sExportedModule = "C:\Documents\MyMacro.bas"
Const sMacroName = "MyMacro"
Dim oFSO, oFDR, oFile ' File and Folder variables
Dim oExcel, oWB ' Excel variables (Application and Workbook)
Start
'------------------------------
Sub Start()
Initialize
ProcessFilesInFolder sRootFolder
Finish
End Sub
'------------------------------
Sub ProcessFilesInFolder(sFolder)
' Process the files in this folder
For Each oFile In oFSO.GetFolder(sFolder).Files
If IsExcelFile(oFile) Then ProcessExcelFile oFile.Path
Next
End Sub
'------------------------------
Sub Initialize()
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oExcel = CreateObject("Excel.Application")
End Sub
'------------------------------
Sub Finish()
oExcel.Quit
Set oExcel = Nothing
Set oFSO = Nothing
End Sub
'------------------------------
Function IsExcelFile(oFile)
IsExcelFile = (InStr(1, oFSO.GetExtensionName(oFile), "xls", vbTextCompare) > 0) And (Left(oFile.Name, 1) <> "~")
End Function
'------------------------------
Sub ProcessExcelFile(sFileName)
On Error Resume Next
wscript.echo "Processing file: " & sFileName ' Comment this unless using cscript in command prompt
Set oWB = oExcel.Workbooks.Open(sFileName)
oWB.VBProject.VBComponents.Import sExportedModule
oExcel.Run sMacroName
oWB.Save
oWB.Close
Set oWB = Nothing
End Sub
'------------------------------
Here is a vbs code for a single file which works:
Option Explicit
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Dim objWorkbook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Documents\test.xls", 0, True)
Set objWorkbook = xlApp.Workbooks.Open("C:\Documents\test.xls")
xlApp.Run "MyMacro"
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
I finally got it working:
Const sRootFolder = "C:\Documents"
Const sExportedModule = "C:\Documents\MyMacro.bas"
Const sMacroName = "Trip"
Dim oFSO, oFile ' File and Folder variables
Dim xlApp, xlBook, objWorkbook
Start
Sub Start()
Initialize
ProcessFilesInFolder sRootFolder
Finish
End Sub
Sub ProcessFilesInFolder(sFolder)
' Process the files in this folder
For Each oFile In oFSO.GetFolder(sFolder).Files
If IsExcelFile(oFile) Then ProcessExcelFile oFile.Path
Next
End Sub
Sub Initialize()
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set xlApp = CreateObject("Excel.Application")
End Sub
Sub Finish()
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Set oFSO = Nothing
End Sub
Function IsExcelFile(oFile)
IsExcelFile = (InStr(1, oFSO.GetExtensionName(oFile), "xls", vbTextCompare) > 0) And (Left(oFile.Name, 1) <> "~")
End Function
Sub ProcessExcelFile(sFileName)
wscript.echo "Processing file: " & sFileName ' Comment this unless using cscript in command prompt
Set xlBook = xlApp.Workbooks.Open(sFileName, 0, True)
Set objWorkbook = xlApp.Workbooks.Open(sFileName)
objWorkbook.VBProject.VBComponents.Import sExportedModule
xlApp.Run sMacroName
End Sub
Also, make sure that Trust access to the VBA project object model enabled. I certainly may be wrong, but the game changer here seems to be this piece:
Set objWorkbook = xlApp.Workbooks.Open(sFileName)

Open File dialog box to get Excel

I've written some Word VBA which takes an Excel file and updates Labels (ActiveX Control) in the Word file. The only thing is this Excel file will change path and filename each month. Instead of editing 2 variables each month, how do I add an Open File dialog box so the user selects the Excel file to be used?
Here is what I have now:
Sub Update()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
PathWork = "C:\My Documents\2015-05 Report\"
CalcFile = "May2015-data.xlsx"
Set exWb=objExcel.Workbooks.Open(FileName:=PathWork & CalcFile)
ThisDocument.date.Caption=exWb.Sheets("Data").Cells(1,1)
End Sub
Here is a simplified macro which will allow the user to select only Macro-Enabled Excels. I couldn't comment on the previous answer as I have not earned enough reputation to comment on an answer. Please mind it.
Public Sub GetCaptionFromExcel()
Dim objExcel As New Excel.Application, exWb As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select Macro-Enabled Excel Files"
.Filters.Add "Macro-Enabled Excel Files", "*.xlsm", 1
If .Show <> -1 Then Exit Sub
Set exWb = objExcel.Workbooks.Open(.SelectedItems(1))
'*** Use the values from excel here***
MsgBox exWb.Sheets("Data").Cells(1, 1)
'*** Close the opened Excel file
exWb.Close
End With
End Sub
You could try something like this
Replace PathWork and CalcFile with Dialogbox
With Dialogs(wdDialogFileOpen)
If .Display Then
If .Name <> "" Then
Set exWb = Workbooks.Open(.Name)
sPath = exWb.Path
End If
Else
MsgBox "No file selected"
End If
End With
Complete CODE should look like this
Option Explicit
Sub Update()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim sPath As String
'// Dialog box here to select excel file
With Dialogs(wdDialogFileOpen)
If .Display Then
If .Name <> "" Then
Set exWb = Workbooks.Open(.Name)
sPath = exWb.Path
End If
Set exWb = objExcel.Workbooks.Open(FileName:=sPath)
ActiveDocument.Date.Caption = exWb.Sheets("Data").Cells(1, 1)
Else
MsgBox "No file selected"
End If
End With
Set objExcel = Nothing
Set exWb = Nothing
End Sub

Modify VBS – Excel Macro Loop Apply to all files in folder

I have a script that applies a macro to multiple excel spreadsheets. The code below opens specific file names and runs the script. I would love to modify this to run on all xls files within a specified folder. Any help would be great!
Dim objExcel, objWorkbook, xlModule, strCode
If ReportFileStatus("C:\Billing\Import\IL\3.xls") = "True" Then
OpenFile "C:\Billing\Import\IL\3.xls, ""
If ReportFileStatus("C:\Billing\Import\IL\3.xls") = "True" Then
OpenFile "C:\Billing\Import\IL\3.xls", ""
If ReportFileStatus("C:\Billing\Import\IL\3.xls") = "True" Then
OpenFile "C:\Billing\Import\IL\3.xls", ""
End If
On Error Resume Next
Set xlModule = Nothing
Set objWorkbook = Nothing
objExcel.Quit
Set objExcel = Nothing
On Error GoTo 0
'~~> Sub to open the file
Sub OpenFile(sFile, DestFile)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = false
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open(sFile)
Set xlModule = objWorkbook.VBProject.VBComponents.Add(1)
strCode = _
"Sub MACRO()" & vbCr & _
'~~> My Macro Here
"End Sub"
xlModule.CodeModule.AddFromString strCode
objExcel.Run "MACRO"
objWorkbook.Close (False) '<~~ Change false to true in case you want to save changes
objExcel.Application.Quit
End Sub
'~~> Function to check if file exists
Function ReportFileStatus(filespec)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = "True"
Else
msg = "False"
End If
ReportFileStatus = msg
End Function
Thanks
The concept is pretty simple, given a folder path, process all files in it (or only certain files based on extension), and all files within it's subfolder. The simplest method is recursive subs and functions with some global variables in a single thread.
The next thing to consider is to Import .bas file instead of trying to add text to a new module. You need to export a working code from a Module first.
Below assumed the root folder to be "C:\Billing\Import", the exported module .bas file is "C:\Test\Module1.bas", and the Sub name you want to execute is "MACRO".
Const sRootFolder = "C:\Billing\Import"
Const sExportedModule = "C:\Test\Module1.bas"
Const sMacroName = "MACRO"
Dim oFSO, oFDR, oFile ' File and Folder variables
Dim oExcel, oWB ' Excel variables (Application and Workbook)
Start
'------------------------------
Sub Start()
Initialize
ProcessFilesInFolder sRootFolder
Finish
End Sub
'------------------------------
Sub ProcessFilesInFolder(sFolder)
' Process the files in this folder
For Each oFile In oFSO.GetFolder(sFolder).Files
If IsExcelFile(oFile) Then ProcessExcelFile oFile.Path
Next
' Recurse all sub-folders from this folder
For Each oFDR In oFSO.GetFolder(sFolder).SubFolders
ProcessFilesInFolder oFDR.Path
Next
End Sub
'------------------------------
Sub Initialize()
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oExcel = CreateObject("Excel.Application")
End Sub
'------------------------------
Sub Finish()
oExcel.Quit
Set oExcel = Nothing
Set oFSO = Nothing
End Sub
'------------------------------
Function IsExcelFile(oFile)
IsExcelFile = (InStr(1, oFSO.GetExtensionName(oFile), "xls", vbTextCompare) > 0) And (Left(oFile.Name, 1) <> "~")
End Function
'------------------------------
Sub ProcessExcelFile(sFileName)
On Error Resume Next
wscript.echo "Processing file: " & sFileName ' Comment this unless using cscript in command prompt
Set oWB = oExcel.Workbooks.Open(sFileName)
oWB.VBProject.VBComponents.Import sExportedModule
oExcel.Run sMacroName
oWB.Close
Set oWB = Nothing
End Sub
'------------------------------
Feel free to ask if you get stuck understanding the program flow.

VBA: Cannot implement Excel VBS outside of excel

I have the code shown below, which opens a workbook and runs the corresponding macro. Running this script through excel works just fine, but running the .vbs file with the same code does not run the macro. I have tried both double clicking the file and running it through the cmd prompt with "cscript.exe LaunchMacro.vbs". In addition, using WScript.Echo does not print to my command line. Am i missing something here?
Thank you!
Option Explicit
Sub LaunchMacro()
Dim xlApp, xlBook
Dim oShell: Set oShell = CreateObject("WScript.Shell")
oShell.CurrentDirectory = "H:"
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Application.Visible = False
Set xlBook = xlApp.Workbooks.Open("H:\SW Tool Resources\test\tester.xlsm")
MsgBox ("File Opened")
xlApp.DisplayAlerts = False
xlApp.Application.Run ("tester.xlsm!Module3.split")
MsgBox ("Application Should Have Run")
xlBook.Saved = True
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
VBS and VBA are different.
Try to put only this code in the vbs file and run it:
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Application.Visible = False
Set xlBook = xlApp.Workbooks.Open("H:\SW Tool Resources\test\tester.xlsm")
MsgBox ("File Opened")
xlApp.DisplayAlerts = False
xlApp.Application.Run ("tester.xlsm!Module3.split")
MsgBox ("Application Should Have Run")
xlBook.Saved = True
xlApp.Quit
I didn't test it, and very likely will not succeed. But it should put it in the right direction.
Edit:
Here is something that should help you getting started with VBS: a script can define some functions, but only runs them if you call them.
For example this will only run Sub1:
Sub Sub1()
MsgBox "1"
End Sub
Sub Sub2()
MsgBox "2"
End Sub
Sub1

Resources