vba Excel - How to Check if a SharePoint Website File is Open - vba

I've searched the internet for the answer to this and keep running into issues getting it to work.
I need to check if a file at the below location is open/locked, and then have the code wait 15 seconds and then try again. Right now if someone else has the file open a dialog box opens asking if I want to open read only, which I don't want. I tried using Application.DisplayAlerts = False to get the message not to appear but that didn't seem to work. So I have two main issues:
Checking if the file is open and waiting to try again.
Stop the dialog box from opening asking to open as read only.
Workbooks.Open filename:= _
"https://somecorporatewebsite/sites/TNKYWest/Engr/ASE%20Updates/Shared%20Documents/ASENW Updater.xlsx"

Try something like this:
From MSDN site:
https://msdn.microsoft.com/en-us/library/office/ff193284.aspx
Sub UseCanCheckOut(docCheckOut As String)
Dim docCheckout
set docCheckout="File name to open"
' Determine if workbook can be checked out.
If Workbooks.CanCheckOut(Filename:=docCheckOut) = True Then
Workbooks.CheckOut (Filename:=docCheckOut)
Else
Found at the MSDN Website:
https://msdn.microsoft.com/en-us/library/office/ff822851.aspx
Application.Wait(Now + TimeValue("0:00:10"))
Workbooks.CheckOut (Filename:=docCheckOut) 'Try to check the file out again.
End If
End Sub
This part is covered in the
IF workbooks.cancheckout(filename:=docCheckout)=true then workbooks.checkout ' method in part 1.

Related

How to change default path in save on close prompt?

I'm trying to create a template that automatically changes folder suggested by the save prompt to a specified location. I've managed to get it partially working using the following code (modified from here):
Sub FileSave()
Dim UserSaveDialog As Dialog
Set UserSaveDialog = Dialogs(wdDialogFileSaveAs)
'save changes if doc has been saved previously
If ActiveDocument.Path <> "" Then
ActiveDocument.Save
Exit Sub
End If
With UserSaveDialog
.Name = "C:\Users\david\Downloads"
If .Display Then
UserSaveDialog.Execute
End If
End With
End Sub
Using this code, my macro correctly intercepts the default save behaviour (or Ctrl+S), however it doesn't intercept the save dialog when closing the file. I've tried basically copying this code to a new Sub called Document_BeforeSave, FileExit, FileCloseEx and FileCloseAllEx (yes, I am having difficulty with all the different objects and what they do :) all to no avail.
I'm not sure the same code will even work in this event, but I don't even get any indication that it has failed to work, so it seems I'm using the wrong event.
Turns out I somehow missed AutoClose (MS Docs), which does what I want.

Access autocad object properties without opening it by VBA

I have been using folder browser for VBA, I could paste the code of it, but bottom line is that I get returned file name as a string.
Is there any way to access drawing properties (i.e number of layouts) without open?
Public Sub TestFileDialog()
dwgname = FileBrowseOpen("C:", "*", ".dwg", 1) 'dwgname is typeof string
End Sub
Its only the first step (use of FileBrowseOpen function is shown, but also i can use FolderBrowse and collect all .dwg inside of folder),actually i had in mind to batch export all layouts of selected .dwgs to currenty open one. Is there any chance for that?
To effectively read a .dwg file you'll need to open AutoCAD, otherwise the information is not accessible. Some properties may be, such as author, but not number of layouts...
But you can use AutoCAD Console (accoreconsole.exe) to run a headless AutoCAD and use APIs to read any information you need. This is really fast for reading lot's of files and the user will not see it running (but it needs to be installed anyway).
http://aucache.autodesk.com/au2012/sessionsFiles/3338/3323/handout_3338_CP3338-Handout.pdf
you could stay in VBA and use ObjectDBX
it leads to a very similar approach as accoreconsole.exe on in .NET does, i.e you won't see any drawing open in UI since it works on the database itself
It requires adding library reference (Tools->References) to "AutoCAD/ObjectDBX Common XX.Y Type Library", where "XX.Y" is "19.0" for AutoCAD 2014
a minimal functioning code is
Sub main()
Dim myAxDbDoc As AxDbDocument
Dim FullFileName As String
FullFileName = "C:\..\mydrawing.dwg" '<== put here the full name of the file to be opened
Set myAxDbDoc = AxDb_SetDrawing(FullFileName)
MsgBox myAxDbDoc.Layers.Count
End Sub
Function AxDb_SetDrawing(FullFileName As String) As AxDbDocument
Dim DBXDoc As AxDbDocument
Set DBXDoc = Application.GetInterfaceObject("ObjectDBX.AxDbDocument.19") '<== place correct AutoCAD version numeber ("19" works for AutoCAD 2014)
On Error Resume Next
DBXDoc.Open FullFileName
If Err <> 0 Then
MsgBox "Couldn't open" & vbCrLf & vbCrLf & FullFileName, vbOKOnly + vbCritical, "AxDB_SetDrawing"
Else
Set AxDb_SetDrawing = DBXDoc
End If
On Error GoTo 0
End Function
Still, you must have one AutoCAD session running from which make this sub run! But you should have it since talked about "currently open" drawing

Adobe "Save as" dialog boxes - MapPoint Excel VBA

I am trying to interact with an external Acrobat dialog window through VBA.
I am using MapPoint to generate maps and then save them as PDF files. Everything is controlled through VBA. I am using the "PrintOut" method of the maps to save them.
objApp.ActiveMap.PrintOut _
Title:=PDFTitle, _
PrintArea:=geoPrintFullPage, _
PrintQuality:=geoPrintQualityNormal, _
PrintOrientation:=geoPrintLandscape
Using this command in this way launches a "Save PDF file as" dialog box. At some point in the past we used to deal with this issue by using the SendKeys function to send {Enter} to the dialog and close it, but this no longer works.
I think the problem is that running this command causes VBA execution to stop until the dialog box is closed. Is there any way I could schedule a Sendkeys function to execute after the dialog opens? Or is there a way to prevent VBA execution from pausing?
Ideally, I would like to avoid having the dialog box in the first place, but that does not appear to be possible with my current setup. Specifying the OutputFileName when running the command does prevent the dialog from appearing, but it causes some kind of problem with the saved file (it can't be opened and appears to be corrupt).
Any suggestions are appreciated!
Can you download primopdf and try the following. PrimoPdf is a free print driver that allows you to save as PDF. http://download.cnet.com/PrimoPDF/3000-18497_4-10264577.html
Option Explicit
Sub PrintToPrimoPDF()
Dim strCurrentPrinter As String
strCurrentPrinter = Application.ActivePrinter ' save the currently active printer
On Error Resume Next ' ignore errors
Application.ActivePrinter = "PrimoPDF on Ne04:" ' change to PrimoPdf
Sheet1.PrintOut ' print the sheet1
Application.ActivePrinter = strCurrentPrinter ' change back to the original printer
On Error Goto 0 ' resume normal error handling
End Sub

How to click on this particular button from VBA?

I have a simple VBA code (see below), that goes to a webpage, selects some value, clicks the “Begin download” button, and then saves the file. The problem is I am stuck at the “clicking the download button” part. Can someone help?
Here is the code:
Sub Treasury_Auc_Notes()
Dim IE As Object
Set IE = Nothing
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "http://www.treasurydirect.gov/RI/OFAuctions?form=ndnld&typesec=notes"
While IE.Busy
DoEvents
Wend
IE.Document.All.Item("begYr").Value = "2012"
With IE.Document.getElementsByName("cols")
.Item(0).Checked = True
End With
'Click "Begin download" button (this is where I am stuck)
'Choose Save Open or Cancel (I haven’t got to this part yet)
ActiveWorkbook.SaveAs Filename
End Sub
This one's tricky, and due to restrictive security on my laptop, I'm not able to verify this 100%, but try:
While IE.ReadyState <> 4
DoEvents
Wend
IE.Document.All.Item("begYr").Value = "2012"
With IE.Document.getElementsByName("cols")
.Item(0).Checked = True
End With
Dim ele As Object
For Each ele In IE.Document.Forms
If ele.Action = "/RI/OFAuctions" Then
ele.Submit
Exit For
End If
Next
You may have to use SendKeys (I think Application.SendKeys "o") method to open the file then use VBA to save the ActiveWorkbook to the desired location. I'm not able to test SendKeys for reasons mentioned below.
Or, I'm pretty sure there is a WinAPI functions that can do this more reliably than SendKeys. You'll need to get the hWnd of the Save dialog and do some other stuff to force it to open/save. This is fairly advanced VBA that I probably have a reference to somewhere, but rarely need to use it. If you have trouble with this particular part, I would urge you to ask a separate question "How to get the hWnd of File Save dialog and download file from IE" or something like that.
NOTE: I can't test the SendKeys method. When I use the above code, I am fairly certain the file is being downloaded, but it is going to a temporary folder that is hidden, and difficult to find. In any case, it does appear to be downloading with some manual intervention. I get this warning:
I click to ignore that (I have no idea how to automate this part, I'm just trying to validate that the form .Submit method actually worked), and after some creative searching (temporary internet files get dumped in a strange/hidden folder usually) I verify the file is downloaded, although it is showing as a TXT extension instead of CSV.
If instead of using VBA, I click on the button manually, and I choose to "open" the file opens as CSV and has the same path to that temporary internet location.

Skip automatically pop up for protected workbooks

I use at the moment the following command to open a set of workbooks one by one:
Workbooks.Open Filename:=fFile, Password:="", UpdateLinks:=xlUpdateLinksNever, ReadOnly:=False
Normally the files are open in write-enabled mode, which is what I want. But for some files, the previous line pops up the following window:
In this case, I need to press Read Only to open it. Even though it is read-only, it is still good to be able to open it.
So to conclude, I try to open files in write-enabled mode, if it is not possible for some files, opening them in read-only is still fine. But as the number of the files is huge, I really want to automatize it, and avoid this pop-up. Could anyone tell me how to do it?
One possible turnaround is to first opening all the files in read-only mode, then convert them to write-enabled mode if possible. Do you think that is doable?
This is possible workaround for you. The idea is to pass any incorrect password to WriteResPassword argument. If file is protected the error will be thrown. If so you will be able to identify that file and open it in read-only mode. Alternatively, password will be ignored for other files and fill will be open for read-write mode.
Some additional comments within code below.
Sub PossibleWorkaround()
Dim Pass As String
'any password
Pass = "blahblah"
'file which is write-protected will throw error during opening it _
with incorrect password
On Error Resume Next
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , , , , Pass
If Err.Number = 1004 Then
'if so, try to open it in read-only mode
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , True
End If
'return to standard error handling or set as expected
On Error GoTo 0
'the same for file which is not write-protected
'incorrect password will be ignored
On Error Resume Next
Workbooks.Open "c:\users\alpha\desktop\filename A.xlsx", , , , , Pass
If Err.Number = 1004 Then
'therefore this if statement will not be called
Workbooks.Open "c:\users\alpha\desktop\filename.xlsx", , True
End If
On Error GoTo 0
End Sub
I had the same problem. I tired to find the answer on many formums and nothing. Finally I added WriteResPassword:="password here" in the end of the Worksbooks.Open statement and it did not prompt for a password anymore
Workbooks.Open Filename:="\path to the file\File_name.xlsm", Password:="password here", WriteResPassword:="password here"