I am trying to create a text file in lotus notes which I am running through the agents. The agent ran successfully but the text file is not created in the path which is specified in the lotus script.
This is the lotus script code:
Option Public
Sub Initialize
MsgBox " Agent AccessUserList"
On Error GoTo HandleError
Dim session As New NotesSession
Dim myStream As NotesStream
Dim TheDate As String, filename As String
TheDate=Format(Now(),"mmdd")
filename = "C:"+"\red"+"\color"+TheDate+".txt"
MsgBox filename
Set myStream = session.Createstream()
MsgBox "MySTREAM2"
Call myStream.Open(filename, "ASCII")
MsgBox "MySTREAM3"
Call myStream.Truncate()
MsgBox "Entered View"
closeFile:
Call myStream.Close()
MsgBox "Closed"
Exit Sub
HandleError:
MsgBox "Error - " & Error &" at line number " & Erl
Exit Sub
End Sub
I have scheduled to 5 min to check whether it creates a new file in specified folder
enter image description here
And also the privileges while scheduling I used both second and third
Allow restricted operations
Allow Restricted operations with full administrator rights
But still it shows the folder as empty but the folder time would be changed when this it gets scheduled.
To test it i scheduled the agent to run locally as well as in the server. But the error is same the text file is not created.
Agent log is not having any errors.
enter image description here
I have checked in the logs as well and there is no errors. Can anyone tell what is the mistake in the above code and why my file is not getting created when the agent executes correctly.
NotesStream doesn't work for you as you just want to create an empty file.
Call myStream.Close() always deletes just now created file if it's empty at this point.
Use traditional FreeFile()/Open/Close instead:
Sub Initialize
On Error GoTo HandleError
Dim TheDate As String
Dim filename As String
Dim fileNum As Integer
TheDate = Format(Now(),"mmdd")
filename = "C:\red\color" + TheDate + ".txt"
fileNum = FreeFile
Open filename For Output As fileNum
Close fileNum
Finally:
Exit Sub
HandleError:
MsgBox "Error - " & Error &" at line number " & Erl
Resume Finally
End Sub
When a stream is truncated, property values are: • Bytes is 0 • IsEOS
is True • Position is 0
Closing a stream with zero bytes deletes the associated file.
Your file is getting created and then deleted because it's empty.
Related
I have a Microsoft project vba application where I want to copy a selection of tasks using the "marked" field to identify all of the predecessor tasks to a target task, identified as the "target" below. When I have traced the network back to include only incompleted tasks, control passes to a routine which uses DocumentExport to create a copied file and save it to a pdf. Then, using ActiveSheet.OLEObjects.add, take this PDF and copy to a specific excel Tab with the "A3" cell being the top/left corner for the file to be placed.
excerpts of my current code:
target = ActiveCell.Task
SaveFilePath = "C:\Macros\"
SaveFileName = SaveFilePath & "Target-" & target & ".pdf"
SaveFilePath = "C:\Macros\"
SaveFileName = SaveFilePath & "Target-" & target & ".pdf"
Application.FilePageSetupView Name:=".MarkedPred_View", allsheetcolumns:=True, BestPageFitTimescale:=True
Application.FilePageSetupPage Name:=".MarkedPred_View", Portrait:=False, PagesTall:=6, PagesWide:=1, PaperSize:=pjPaperLegal, FirstPageNumber:=False
StrHeader = "&18&B" & GetFontFormatCode("Calibri") & "Status Date=" & Format(ActiveProject.StatusDate, "mm/dd/yy") & " Task Name= " & SelTask.Name & " ID:" & SelTask.ID & " UID:" & SelTask.UniqueID
Application.FilePageSetupHeader Name:=".MarkedPred_View", Alignment:=pjCenter, Text:=StrHeader
Application.FilePageSetupLegend Name:=".MarkedPred_View", LegendOn:=pjNoLegend
DocumentExport SaveFileName, pjPDF, FromDate:=EarliestStart - 30, ToDate:=LFin + 30
xlsheet.Range("A3").Select
ActiveSheet.OLEObjects.Add(FileName:=SaveFileName, Link:=True _
, DisplayAsIcon:=False).Activate
If I set the Link property to false, the copy to excel does not happen
sbDeleteAFile (SaveFileName)
Sub DeleteAFile(ByVal FileToDelete As String)
IsFileOpen (FileToDelete)
SetAttr FileToDelete, vbNormal
Kill FileToDelete
End Sub
Function IsFileOpen(FileName As String)
Dim filenum As Integer, errnum As Integer
OutputStr = ("1587 - IsFileOpen - started for = " & FileName) 'added
Call Txt_Append(MyFile, OutputStr)
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open FileName For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
Case 0
IsFileOpen = False
'Open (Filename)
' Error number for "Permission Denied."
' File is already opened by another user.
OutputStr = ("1587 - IsFileOpen - is NOT Open") 'added
Call Txt_Append(MyFile, OutputStr)
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
OutputStr = ("1587 - IsFileOpen - IS Open") 'added
Call Txt_Append(MyFile, OutputStr)
Error errnum
End Select
End Function
"LFin" is the finish date of the target task, from which I am collecting all of its predecessors. I am using the finish date as the "Latest Finish" (LFIN) to bound the "ToDate" in the command.
The error appears with the "ActiveSheet.OLEObjects.Add (fileName:=SaveFilename, Link:=True _" command, where the PDF is opened and copied to the specified excel tab with cell "A3" being the point of the paste for the image.
I do not have any code to close the PDF in this snippet so I get an error when I try to delete an open file. I have seen lots of discussion on various boards where if a file is opened by another application, MS Project VBA cannot delete it as it does not have the handle to the file (??). If I manually close the PDF, close the error notification in the debugger and then press "Run/Continue" , the PDF is deleted and cycles back through the main routine, just like I want it to but I have to again close the newly created PDF, clear the dialog and select Run/Continue.
The only section of this code which does not work as desired (and is currently missing in this code) is having the ability to close the PDF after it has been copied to Excel as it is no longer needed. I have only seen very complicated code which gets the handle of the PDF and then allows you to close the specific file without affecting any other PDF files which may also be open and are not part of this process.
Does anyone have any ideas? I first started using CopyToClipboard, but this command only can copy 16 rows of MS Project schedule to the clipboard. Then, I tried ExportAsFixedFormat, but the FromDate and ToDate entries have no effect on the displayed image.
Using DocumentExport and Application.OLEObjects.Add allows me to copy unlimted pages of schedule to the clipboard and paste into an excel tab showing the desired dates only.This is the closest I have been able to come to get what I want the output to look like. I have been unable to find an associated command to Application.OLEObjects.Add command which I can use to close the PDF file created by the Application.OLEObjects.Add. It certainly makes sense that you want to open the PDF file so it can be copied to the Excel tab, but it is surprising there is not also an easy way to close that PDF file after it has served its purpose.
The question boils down to this:
The error appears with the "ActiveSheet.OLEObjects.Add
(fileName:=SaveFilename, Link:=True, DisplayAsIcon:=False).Activate" command, where the PDF is
opened and copied to the specified excel tab...
The reason the pdf file opens is that the code is telling it to. By using the Activate method on the OLEObject just added, it activates it--meaning in opens the pdf file.
The solution is to simply the OLEObjects.Add method to this:
ActiveSheet.OLEObjects.Add FileName:=SaveFileName
There are multiple Excel files on a server (or network shared storage location).
I have an Access document that needs access to these Excel files to execute a certain function.
When one of these files is open I can not execute my VBA function.
I check if someone is using the file. This is in the code below.
Is it is possible to also find out who is using a file. I would notify them to close the file(s).
Some of the things I tried (these are not all, but I can’t find a few methods anymore that I tried too):
https://chandoo.org/forum/threads/return-user-name-who-has-file-open.31447/
https://www.ozgrid.com/forum/forum/help-forums/excel-general/87346-vba-code-to-determine-who-has-file-open
In the last one they get the owner of the file and that is not the same as the one that is using the file at that moment. I tried it, but even then I sometimes get a username, but the username of the one that created the file and sometimes I get a SID (Security Identifier?).
Code to find out if the file is in use. This does not include anything to see who is using the file.
Sub TestFileOpened()
Dim filesArray As Variant
filesArray = Array("Map1.xlsx", "Map2.xlsx")
Dim fileLocation As String
fileLocation = "\\DESKTOP-NETWORK\SharedFolder\NetwerkTest\"
Dim message As String
For Each file In filesArray
If IsFileOpen(fileLocation & file) Then
message = message & vbNewLine & "File '" & file & "' is open!"
'Else
' message = message & vbNewLine & "File '" & file & "' is closed!"
End If
Next file
MsgBox message
End Sub
Function to check if the file is in use:
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next
filenum = FreeFile()
Open filename For Input Lock Read As #filenum
Close filenum
errnum = Err
On Error GoTo 0
Select Case errnum
Case 0
IsFileOpen = False
Case 70
IsFileOpen = True
Case Else
Error errnum
End Select
End Function
Access and Excel are able to do exactly that when you try to manually open the file. Superuser post: https://superuser.com/questions/845084/how-to-get-excel-to-show-username-of-person-that-has-file-open
Ok, i am not good in writing descent macro's, so modify code to suit your own needs!
This one should give the name of the user who has currently opened an Excel-sheet:
Sub InUse(filename As String)
Dim f
Dim i
Dim x
Dim inUseBy
Dim tempfile
tempfile = Environ("TEMP") + "\tempfile" + CStr(Int(Rnd * 1000))
f = FreeFile
i = InStrRev(filename, "\")
If (i > 0) Then
filename = Mid(filename, 1, i) + "~$" + Mid(filename, 1 + i)
Else
filename = "~$" + filename
End If
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile filename, tempfile
Open tempfile For Binary Access Read As #f
Input #f, x
Close (f)
inUseBy = Mid(x, 2, Asc(x))
fso.Deletefile tempfile
Set fso = Nothing
MsgBox "InUse by: " + inUseBy, vbOKOnly, "InUse"
End Sub
Example use:
InUse("T:\Book1.xlsx")
Things to note:
This should be used when opening of a sheet fails (because of bein in-use)
I did not find any documentation about this being the 'valid' way to do this.
I do not know if this also works with shared excel sheets
Whenever a specific Excel file is in use, I'd like to prevent anyone else editing it.
ie. "This file is currently being edited by John Dow, and it will now close".
I'm looking for something simple.
Any ideas?
Thank you,
D.
I'm going to add an answer to this which I'll have to say is nowhere near perfect (blatantly trying to avoid down-votes for trying to do something that isn't really necessary).
I just wanted to see if you could extract the name of the person that has it open - after all, it does normally give the name of the person who has it locked for editing when you first open a workbook.
When you open an Excel file a hidden lock file is created in the same folder. The lock file has the same name as the original with ~$ appended to the front of the file name.
I found you can't copy the lock file using the VBA FileCopy as you get a Permission denied error, but you can using the FileSystemObject CopyFile.
The thinking behind my method is to copy the lock file and change it to a text file. You can then pull the user name from it and compare it against the current user name - if it's different then report that and close the file.
Note - I wouldn't use this in a project as there seems to be a few places it can fall over, and Excel will generally tell you that someone else has it open anyway. It was more of a coding exercise.
Private Sub Workbook_Open()
Dim ff As Long
Dim sLockFile As String
Dim sTempFile As String
Dim oFSO As Object
Dim XLUser As String, LoggedUser As String
Dim fle As Object
sLockFile = ThisWorkbook.Path & Application.PathSeparator & "~$" & ThisWorkbook.Name
sTempFile = Replace(sLockFile, "~$", "") & "tmp.txt"
'Create copy of lock file as a text file.
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.CopyFile sLockFile, sTempFile, True
'Read the first line from the text file.
ff = FreeFile()
Open sTempFile For Input Lock Read As #ff
Line Input #1, XLUser
Close ff
'Remove the current user from the text.
'Need to check this so that it doesn't close because it sees the current user name.
XLUser = Replace(XLUser, Application.UserName, "")
'Extract name from text string.
'There is a double space in the InStr section.
'The double exclamation mark is a single character - I don't know the code though.
'Unicode U+0203C I think.
XLUser = Replace(Left(XLUser, InStr(XLUser, " ") - 1), "", "")
'Remove hidden attributes so temp file can be deleted.
Set fle = oFSO.GetFile(sTempFile)
fle.Attributes = 0
Kill sTempFile
'If there's still text then it's a user name - report it and close.
If Len(Trim(XLUser)) > 0 Then
MsgBox "Workbook is already open by " & XLUser
ThisWorkbook.Close SaveChanges:=False
End If
End Sub
Having put all that, this code is probably safer:
Private Sub Workbook_Open()
If ThisWorkbook.ReadOnly Then
MsgBox "Is opened in read only.", vbOKOnly
ThisWorkbook.Close SaveChanges:=False
End If
End Sub
First post, hello to everyone.
I am looking for code for a button when pressed will prompt the user to change the data connection source file. The following code works to the point of requesting the user to pick a new source file but none of the connections then update with the new filepath, any ideas? Thanks in advance
Sub xlTest()
Dim i As Long
Dim cnt As Long
Dim cn
cnt = ActiveWorkbook.Connections.Count
'Choose a File
strPath = Application.GetOpenFilename(Title:="Choose a file", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If strPath = False Then
MsgBox "No file selected. Exiting now.", vbExclamation
Exit Sub
End If
'Change Connection source filepath for each connection
For i = cnt To 1 Step -1
Set cn = ActiveWorkbook.Connections.Item(i)
cn.OLEDBConnection.SourceDataFile = strPath
Next i
End Sub
I don't understand why are you using the For Next statement, since it looks like you're opening only one file per execution. But I think you can replace the code inside it for ActiveWorkbook.Connections.AddFromFile (strPath), it will prompt you to a dialog to choose a sheet inside to connect, also you don't need to declare your 'cn' variable.
File rename is often requires while working on Microsoft Office Suite applications (Word, Excel, PowerPoint). Usually “Files > Save as” allows rename the file but it also create duplication since the original file remain there and there is no simultaneous options to delete the original file. Although this option is currently in practice but for quick and convenient rename without any duplication of same file the current available option is not adequate. Close the file, remember its name and locate that file in the residing specific directory (where file is masked by similar other files) is possible but the approach is very time consuming and not a good solution to improve productivity.
Obviously that leads to need of a single click quick option which would allow rename of the file which would also delete the old file or overwrite on existing file. AFAIK the Office suite applications / Windows explorer does not allow renames the file while it opens (file locked). So to my understanding and reading from other similar questions in this forum this is might be technical limitation and might not possible to rename active (locked) file. However I have seen a solution of this kind in Sumatra PDF reader where the file is PDF and pressing F2 button allows not only rename but also option to choose the folder where to keep the renamed file (original folder or elsewhere) without any duplication of file. I am looking forward if their similar VBA commands which would do at least rename the file at original location or some sort of automation in rename process which avoid duplication and/or minimize the efforts necessary to rename. Searched but could not see any Office suite native built-in shortcut key/command to automate the rename process. Closest I found VBA command Shell Environ("windir") & "\Explorer.exe " & ActiveDocument.Path, vbMaximizedFocus allow to locate the folder location only of currently opened file but it does not select/highlight that specific file and difficult to distinguish if there similar other files in that folder. Thanks in advance for your support contribution.
The correct approach is not via the Explorer shell, instead:
1) Store the full path of the document in a string: oldfile = ActiveDocument.FullName
2) SaveAs the document with ActiveDocument.SaveAs
3) Delete the old file with Kill oldfile
All this is from VBA directly, no need to use Explorer shell.
Below are the full codes for all three applications, with prompting the SaveAs dialog, but then also deleting the old file.
You can use this to rename the Excel document:
Sub RenameActiveWorkBook()
Dim oldfile As String
Set myWbook = ActiveWorkbook
If myWbook.Path = "" Then
On Error Resume Next
myWbook.Save
Exit Sub
End If
'1) store current file
oldfile = myWbook.FullName
'2) save as the active document (prompt user for file name)
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = oldfile
If Application.FileDialog(msoFileDialogSaveAs).Show = 0 Then Exit Sub
Application.FileDialog(msoFileDialogSaveAs).Execute
If oldfile = myWbook.FullName Then Exit Sub
'ONLY RENAME: myWbook.SaveAs Filename:=myWbook.Path & Application.PathSeparator & InputBox("Enter new name", "Rename current document", myWbook.Name), AddToMru:=True
'3) Delete the old file with
On Error GoTo FileLocked
Kill oldfile
On Error GoTo 0
Exit Sub
FileLocked:
MsgBox "Could not delete " & oldfile, vbInformation + vbOKOnly, "File is locked"
End Sub
And very similar to this is the PPT:
Sub RenameActivePresentation()
Dim oldfile As String
Set myPPT = ActivePresentation
If myPPT.Path = "" Then
On Error Resume Next
Application.FileDialog(msoFileDialogSaveAs).Show
Application.FileDialog(msoFileDialogSaveAs).Execute
Exit Sub
End If
'1) store current file
oldfile = myPPT.FullName
'2) save as the active document (prompt user for file name)
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = oldfile
If Application.FileDialog(msoFileDialogSaveAs).Show = 0 Then Exit Sub
Application.FileDialog(msoFileDialogSaveAs).Execute
If oldfile = myPPT.FullName Then Exit Sub
'ONLY RENAME: myPPT.SaveAs FileName:=myPPT.Path & "\" & InputBox("Enter new name", "Rename current document", myPPT.Name)
'3) Delete the old file with
On Error GoTo FileLocked
Kill oldfile
On Error GoTo 0
Exit Sub
FileLocked:
MsgBox "Could not delete " & oldfile, vbInformation + vbOKOnly, "File is locked"
End Sub
And just to have it complete, here is the Word macro for the same thing:
Sub RenameActiveDoc()
Dim oldfile As String
Set myDoc = ActiveDocument
If myDoc.Path = "" Then
On Error Resume Next
myDoc.Save
Exit Sub
End If
'1) store current file
oldfile = myDoc.FullName
'2) save as the active document (prompt user for file name)
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = oldfile
If Application.FileDialog(msoFileDialogSaveAs).Show = 0 Then Exit Sub
Application.FileDialog(msoFileDialogSaveAs).Execute
If oldfile = myDoc.FullName Then Exit Sub
'ONLY RENAME: myDoc.SaveAs FileName:=myDoc.Path & Application.PathSeparator & InputBox("Enter new name", "Rename current document", myDoc.Name)
'3) Delete the old file with
On Error GoTo FileLocked
Kill oldfile
On Error GoTo 0
Exit Sub
FileLocked:
MsgBox "Could not delete " & oldfile, vbInformation + vbOKOnly, "File is locked"
End Sub