Good Morning All,
I have fought with this for a few days now, and have not yet found a suitable solution, so I hope somebody can put me out of my misery!
From within an excel document, I have 3 buttons to check out and open 3 documents from a Microsoft Sharepoint Server. 2 files are Excel workbooks, and one is a Word document.
The excel files work absolutely fine, but the Word document always returns 'False' when the .CanCheckOut statement is reached, even though I can manually check it out on MOSS, have the correct permissions etc. I have added the Microsoft Word 11.0 Object Library reference in my Excel VBA.
Here is my code for the excel ones:
Sub CheckOutXL(FullPath As String)
Dim xlApp As Object
Dim wb As Workbook
Dim xlFile As String
xlFile = FullPath
Set xlApp = CreateObject("Excel.Application")
'Determine if workbook can be checked out.
If Workbooks.CanCheckOut(xlFile) = True Then
'Check out file
Workbooks.CheckOut xlFile
'Open File
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
'Otherwise offer the option to open read-only
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
End If
End If
and for the Word one:
Sub CheckOutDoc(FullPath As String)
If Documents(docFile).CanCheckOut = True Then 'This is the one that returns FALSE
Documents.CheckOut docFile
' Set objWord = CreateObject("Word.Application") 'The commented out section was
' objWord.Visible = True 'a second way I tried to open
' objWord.Documents.Open docFile 'the file.
Documents.Open Filename:=docFile
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Documents.Open Filename:=docFile
End If
End If
End Sub
These are both called using a simple line for each button as such:
Private Sub btnTrend_Click()
Call CheckOutXL("FullPathOfTheFileInHere.xls")
End Sub
Any help massively appreciated!! Thanks
We are having the same issue. Can you try this:
If CBool(Documents(docFile).CanCheckOut) = True Then
Related
I am getting an Automation error, when Catia is trying to write values in a selected Excel sheet. It's a bit confusing because on the first try of the code there was no error and the values were in the Excel sheet.
I didn't change the code, but on the second try I get:
Run-time error '-2147417846 (8001010a)': Automation error
"The Message filter indicated that the application is busy."
on the line: Set MyXL = GetObject(FPath)
Sub CATMain()
FPath = CATIA.FileSelectionBox("Select the Excel file you wish to put the value in", "*.xlsx", CatFileSelectionModeOpen)
If FPath = "" Then
Exit Sub
End If
Set xlApp = CreateObject("Excel.Application")
Set MyXL = GetObject(, "Excel.Application")
Set MyXL = GetObject(FPath)
MyXL.Application.Visible = True
MyXL.Parent.Windows(1).Visible = True
Dim oSelection As Selection
Set oSelection = CATIA.ActiveDocument.Selection
Dim oProduct As AnyObject
On Error Resume Next
Set oProduct = oSelection.FindObject("CATIAProduct")
If (Err.Number <> 0) Then
MsgBox "No selected product"
Else
On Error GoTo 0
Dim oInertia As AnyObject
Set oInertia = oProduct.GetTechnologicalObject("Inertia")
Dim dMass As Double
dMass = oInertia.Mass
Dim dDen As Double
dDen = oInertia.Density
MsgBox oProduct.Name & ": Masse = " & CStr(dMass) & " KG" & ": Dichte = " & (CStr(dDen) / 1000) & " "
MyXL.Application.Cells(1, 1).Value = "Masse"
MyXL.Application.Cells(2, 1).Value = dMass
MyXL.Application.Cells(1, 2).Value = "Dichte"
MyXL.Application.Cells(2, 2).Value = "dDen"
MsgBox "Werte wurden in Excel eingetragen"
End If
End Sub
It appears you did not set Option Explicit - put it on the first line and it will help you avoid errors. (With it, the compiler will force you to declare all your variables. This will also mean that when you put it in, your code will not work unless you declare all variables.)
The first problem:
Set xlApp = CreateObject("Excel.Application")
Set MyXL = GetObject(, "Excel.Application")
You first create a new instance of Excel with CreateObject and store a reference to it in xlApp (which you subsequently do not use). Then you try to get a reference to an existing Excel instance with GetObject and store its reference in MyXL. This only works reliably because you first create a new instance. Otherwise you could not guarantee that there always is an Excel instance available.
A related problem is, that you don't release/close these instances. If you create an Excel instance, you need to close it with xlApp.Quit after you're done using it, otherwise it will linger around.
Be careful though with instances you took over with GetObject - calling MyXL.Quit will close the instance regardless of what other workbooks are open at that time.
Similarly, if you open a file this way, you need to make sure to close it afterwards. Otherwise you'll run into the problem you experience: Write protected files.
So, to mend your problem: Close all open instances of Excel (best done via Task Manager, as some of them might be invisible). Then adjust your code to only use one reference to an Excel.Application. And finally make sure to .Close the workbook after you've saved it and .Quit your Excel instance. This should hopefully prevent the error from reappearing.
'Dim xlApp As Excel.Application ' early-bound declaration
'Set xlApp = New Excel.Application ' early-bound assignment
Dim xlApp As Object ' late-bound declaration
Set xlApp = CreateObject("Excel.Application") ' late-bound assignment
'Dim wb As Workbook ' early-bound declaration
Dim wb as Object
Set wb = xlApp.Workbooks.Open(FPath)
' stuff you want to do with the workbook
wb.Close SaveChanges:=True
xlApp.Quit
If you can add a reference to the Excel object model in you Catia VBA project (not sure about that), you can comment out the late-bound lines and use the early-bound lines instead. That way you gain the very useful IntelliSense for the Excel objects. Which makes it so much easier to code.
Thank you guys! I've solved the Problem with simply adding the code:
Workbook.Close SaveChanges:=True
I am new to Outlook VBA and am trying to compare the value in the same cell from two different closed workbooks.
I have created an Excel Object upon receiving an attachment from an email that saves the attachment as a CSV file.
I then want to check that the header row within the file matches a master copy which has the same headers in the first row but I am not sure how to reference the sheet names nor the cells using the objects.
I have tried many ways using VBA for Excel but it doesn't seem to work in Outlook.
If any one can assist me it would be greatly appreciated.
Function ConvertXls2CSV(sXlsFile As String)
On Error Resume Next
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim bExcelOpened As Boolean 'Was Excel already open or not
Dim OriginalFile As String
Dim MasterFile As String
Dim Fault As Integer
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")
bExcelOpened = False
Else 'Excel was already running
bExcelOpened = True
End If
Set oExcelWrkBk = oExcel.Workbooks.Open(sXlsFile)
oExcelWrkBk.SaveAs Left(sXlsFile, InStrRev(sXlsFile, ".")) & "csv", xlCSVWindows
/*THIS IS WHERE I WANT TO REFERENCE THE CELLS IN THE WORKBOOKS*/
OriginalFile = oExcelWrkBk.Sheets("PK Price Data").Cells(1, 1).Value
MasterFile = oExcelWrkBk."MasterFile.xls".Sheets("PK Price Data").Cells(1, 1).Value
if OriginalFile = MasterFile then
fault = 1
else fault = 0
end if
oExcelWrkBk.Close False
If bExcelOpened = False Then
oExcel.Quit
End If
End Function
Many Thanks
Melinda
As far as I know, it's not possible to address your references to a closed workbook. You can, however, open it without showing with application.screenupdating = false. When you're done storing your references in some variables, you can simply close the workbooks and set application.screenupdating = true
I'm trying to write a vbscript to be able to checkout an excel file that is stored on sharepoint server.
Currently I can check the file out from SharePoint 2010: Link to open Excel file in edit-mode mode
However, I'm trying to check the file back in but not able to. I've searched and tried the checkout functions per http://msdn.microsoft.com/en-us/library/office/ff194456%28v=office.14%29.aspx but not able to.
Currently the code I have is
Sub CheckInFile
Dim ExcelApp, ExcelSheet, ExcelBook
Dim myURL
myURL = "http://server/Site/excel.xlsx"
Set ExcelApp = CreateObject("Excel.Application")
If (ExcelApp.WorkBooks.CanCheckIn(myURL) = True) Then
msgbox ("here")
ExcelApp.WorkBooks.Open (myURL)
ExcelApp.Application.WorkBooks.CheckIn myURL
ExcelApp.ActiveWorkbook.Close
' Quit Excel.
ExcelApp.Quit
' Clean Up
Set ExcelApp= Nothing
End If
End Sub
However the script stops and fails at the if statement, rather doesn't execute. Is there a similar vbscript function to check in a file ?
I struggled a LOT with this and spent many hours searching for a solution that worked in my particular environment. Here are my criteria that needed to be met:
Execute the process from my computer using vbscript file
Iterate through a list of ~200 excel spreadsheets
Check out each file
Make various conditional updates and save
Check the file back in again when updates are complete.
Below is an alternate solution for anybody in the future that, like me, tried the suggested approach and it didn't work. This is tested and working:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Dim MyVar ' so popup alerts narrate the process
' and help explain what is happening
' for those who want to see it step
' by step
Dim docPath
docPath = "\\your server\sites\Docs\sharepoint spreadsheet.xlsx"
' I believe this can be any document path
Set objWorkbook = objExcel.Workbooks.Open(docPath)
cco = objExcel.Workbooks.CanCheckOut(docPath)
MyVar = MsgBox ("can check out? " & cco, 0)
' -----------------------------------------------------
' this shows "False" every time. I still do not know how
' to get this to work, but thought it would be valuable
' to include for explanation
' -----------------------------------------------------
objExcel.Workbooks.CheckOut(docPath)
' -----------------------------------------------------
' this SUCCEEDS every time...as long as you have
' the ability to check out the document manually
' -----------------------------------------------------
MyVar = MsgBox ("Update cell", 0)
With objExcel.ActiveWorkbook.Worksheets(1)
objExcel.Cells( 1, 1 ).Value = "test value"
End With
MyVar = MsgBox ("Save the file", 0)
objWorkbook.Save
MyVar = MsgBox ("check in the file", 0)
objWorkbook.CheckIn
' -----------------------------------------------------
' This actually checks in the active document and *closes
' it* You don't have to have a separate command to close
' the file, e.g.
' objWorkbook.Close
' THIS WILL FAIL.
' -----------------------------------------------------
Set objWorkbook = Nothing
Just try this:
Dim ExcelApp, ExcelSheet, ExcelBook
Dim myURL = "http://server/Site/excel.xlsx"
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.WorkBooks.Open (myURL)
If (ExcelApp.ActiveWorkbook.CanCheckIn = True) Then
ExcelApp.Application.WorkBooks(myURL).CheckIn
ExcelApp.ActiveWorkbook.Close
' Quit Excel.
ExcelApp.Quit
' Clean Up
Set ExcelApp= Nothing
End If
Just change include below lines to your code:
ExcelApp.Visible = True
ExcelApp.DisplayAlerts = False
Thanks!
Dim oExcel
Dim strFileName
Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oExcel.DisplayAlerts = False
strFileName = "view_2019.xlsm"
'Checkin
If oExcel.Workbooks(strFileName).CanCheckIn = True Then
oExcel.Workbooks(strFileName).CheckIn SaveChanges=True,Comments="Updated"
MsgBox strFileName & " has been checked in."
Else
MsgBox "This file cannot be checked in at this time. Please try again later."
End If
set oExcel = nothing
How to open a Workbook with a password, disable events,
and then copy a sheet in background to the second file and save.
I need in VBA, working in a MS-Access and Excel files
I have done this until now, is working.
Private Sub TestFunction()
'strPath = CurrentDb.Properties(0)
'strPath = Left(strPath, Len(strPath) - Len(Dir(strPath, vbNormal))) & "Temp\"
Dim CopyFrom As Object
Dim CopyTo As Object ''Early binding: Workbook
Dim CopyThis As Object
Dim xl As Object ''Early binding: New Excel.Application
Set xl = CreateObject("Excel.Application")
xl.Visible = True
Set CopyFrom = xl.Workbooks.Open("D:\A01.xls")
'CopyFrom.EnableEvents = False
Set CopyThis = CopyFrom.Sheets(1) ''Sheet number 1
Set CopyTo = xl.Workbooks.Open("D:\PM1.xls")
CopyThis.Copy After:=CopyTo.Sheets(CopyTo.Sheets.Count)
CopyFrom.Close
End Sub
This opens the Excel, I enter the pass copy's the sheet to second File.
But I need to pass the password in background, delete the sheet and save the second file, all in background.
Also I need to delete a sheet, without asking me, like :
CopyTo.Sheets("Sheet1").Delete
Thank you
Password issue
Be careful to check wether it is an "open file" password (password parameter) or a "modify file" password (WriteResPassword parameter).
Something like:
Sub OpenMyFile()
Workbooks.Open Filename:="Path", Password:="OpenFile", WriteResPassword:="WriteFile"
End Sub
Delete without alert
For your second question, here is what you can do:
Application.DisplayAlerts=False
CopyTo.Sheets("Sheet1").Delete
Application.DisplayAlerts=True
I'm trying to run an Excel macro from outside of the Excel file. I'm currently using a ".vbs" file run from the command line, but it keeps telling me the macro can't be found. Here is the script I'm trying to use
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")
objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"
objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
And here is the Macro I'm trying to access:
Sub TestMacro()
'first set a string which contains the path to the file you want to create.
'this example creates one and stores it in the root directory
MyFile = "C:\Users\username\Desktop\" & "TestResult.txt"
'set and open file for output
fnum = FreeFile()
Open MyFile For Output As fnum
'write project info and then a blank line. Note the comma is required
Write #fnum, "I wrote this"
Write #fnum,
'use Print when you want the string without quotation marks
Print #fnum, "I printed this"
Close #fnum
End Sub
I tried the solutions located at Is it possible to run a macro in Excel from external command? to get this far (and modified of course) but it didn't seem to work. I keep getting the error `Microsoft Office Excel: The macro 'Macro.TestMacro' cannot be found.
EDIT: Excel 2003.
Ok, it's actually simple. Assuming that your macro is in a module,not in one of the sheets, you use:
objExcel.Application.Run "test.xls!dog"
'notice the format of 'workbook name'!macro
For a filename with spaces, encase the filename with quotes.
If you've placed the macro under a sheet, say sheet1, just assume sheet1 owns the function, which it does.
objExcel.Application.Run "'test 2.xls'!sheet1.dog"
Notice: You don't need the macro.testfunction notation you've been using.
This code will open the file Test.xls and run the macro TestMacro which will in turn write to the text file TestResult.txt
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
WScript.Quit
Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)
Set objExcel = CreateObject("Excel.Application")
' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"
' Only ran like this (from the Module1)
Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Excel 2010, Win 7
I tried to adapt #Siddhart's code to a relative path to run my open_form macro, but it didn't seem to work. Here was my first attempt. My working solution is below.
Option Explicit
Dim xlApp, xlBook
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open(curDir & "Excels\CLIENTES.xlsb", 0, true)
xlApp.Run "open_form"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only.
2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
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 & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
#echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my 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
Anyway, thanks for your help, and I hope this will help if someone needs it
I tried the above methods but I got the "macro cannot be found" error.
This is final code that worked!
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True
'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)
' Run Macro
xlApp.Run "Sheet1.MyMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.
I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.
Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.
Full Path to Workbook
Macro Name
[OPTIONAL] Path to separate workbook with Macro
I tested it like so:
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"
runmacro.vbs:
Set args = Wscript.Arguments
ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
macrowb= WScript.Arguments.Item(2)
End If
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open(ws, 0, True)
If wscript.arguments.count > 2 Then
Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
End If
'xl.Application.Visible = True ' Show Excel Window
xl.Application.run macro
'xl.DisplayAlerts = False ' suppress prompts and alert messages while a macro is running
'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
'xl.activewindow.close
xl.Quit
End Sub
If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here
oExcel.DisplayAlerts = False
For Each oFile In oFSO.GetFolder("C:\Location\").Files
If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
oExcel.Run wb2.Name & "!modForm"
For Each oSheet In .Worksheets
oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6
Next
.Close False, , False
End With
End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10
So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.
Hi used this thread to get the solution , then i would like to share what i did just in case someone could use it.
What i wanted was to call a macro that change some cells and erase some rows, but i needed for more than 1500 excels( approximately spent 3 minuts for each file)
Mainly problem:
-when calling the macro from vbe , i got the same problem, it was imposible to call the macro from PERSONAL.XLSB, when the script oppened the excel didnt execute personal.xlsb and wasnt any option in the macro window
I solved this by keeping open one excel file with the macro loaded(a.xlsm)(before executing the script)
Then i call the macro from the excel oppened by the script
Option Explicit
Dim xl
Dim counter
counter =10
Do
counter = counter + 1
Set xl = GetObject(, "Excel.Application")
xl.Application.Workbooks.open "C:\pruebas\macroxavi\IA_030-08-026" & counter & ".xlsx"
xl.Application.Visible = True
xl.Application.run "'a.xlsm'!eraserow"
Set xl = Nothing
Loop Until counter = 517
WScript.Echo "Finished."
WScript.Quit