Changing the Folder security permissions using Excel VBA - vba

I am trying to write some code to put a text file into a secure folder. The folder has attributes already set to read-only so that the files within are secure and cannot be altered but still read.
The FileSystemObject will allow me to use the attribute property which I can set to 1 (read-only) but this is easily overridden.
My next port of call was to GetAclInformation etc.
I downloaded some code and I got through a large portion of it but, at GetAclInformation it crashes Excel.
I then continued to look and so used the ADsSecurity dll. This returns an error stating
the ActiveX cannot create the object.
I have downloaded a copy of the dll and put it into the windows\syswow64 directory and then registered it with RegSvr32 which returned a success.
I can add the references required and see the object in the object viewer. But trying both late and early binding has no affect and it still errors saying the ActiveX cannot create the object.
Does anyone have any other ideas or a suggestion on what to try?
Sub TestApproval()
Dim oSec As New ADsSecurity
Dim oSd As Object, oDac1 As Object, oAce As Object
Set oSec = New ADsSecurity
Set oSd = oSec.GetSecurityDescriptor(CStr("FILE://C:\Test"))
Set oDac1 = oSd.DiscretionaryAcl
For Each oAce In oDac1
Debug.Print oAce.trustee & "|" & oAce.AceType & "|" & oAce.AccessMask & "|" & oAce.AceFlags & "|" & oAce.Flags & "|" & oAce.ObjectType & "|" & oAce.InheritedObjectType
Next oAce
Set oSec = Nothing
Set oSd = Nothing
Set oDac1 = Nothing
End Sub
Thanks in advance :)

Related

Filesystemobject Textstream, immediately disappears upon executing Textstream.Close (.vbs extension being created)

I have a situation that is really flummoxing me. Simple code I've used for years is failing in the weirdest way. I have a feeling the cause is related to either anti-virus junk or GPO, but, even those, I have seen them operate before on this scenario--but nothing like how I am seeing it now.
Note - this code has been working perfectly for several people, until one end-user got a new Surface laptop from I.T., purportedly for better compatibility with Teams and 365. ALL users (working, non-working) are on Windows 10.
Scenario:
I'm using Scripting.Filesystemobject
setting an object variable (Textstream intent), as fso.createtextfile
The filepath (name) I am creating is actually filename.vbs...At the moment this line executes, I can see the vbs file successfully in the folder
I use Textstream.Write to put some content in the file
I then use Textstream.Close (normally at this point you get a solid, stable, useable file). Immediately upon execution of the last line, Textstream.Close, the file DISAPPEARS from the folder-GONE.
The folder I'm writing to is the same as Start > Run > %appdata%
I've also tried this in Documents folder (Environ$("USERPROFILE") & "\My Documents") and get the exact same result
I've seen group policies and AV stuff that will prevent VBS from running, but that isn't my case--I've tested with this user, and she has no problem:
Creating a txt file in either of those folders
Manually creating a .vbs file in either of those folders
Even RUNNING the resulting vbs file in either folder
But somehow when I programmatically create .VBS in code, the second I close the textstream, the file is gone from the folder.
Any insight? The internet searches I did were void of all information on this scenario!! It would take me 2 weeks to open a ticket and get any help from I.T.
This is Excel VBA, but I highly doubt the problem has anything to do with Excel nor VBA...this is standard usage of windows scripting.filesystemobject:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'initiate full backup vbs script:
Dim ts As Object, fso As Object, strScriptText As String, strScriptPath As String
'populate our variable with the full text of the script: found on QLoader in this range:
strScriptText = ThisWorkbook.Worksheets("QLoader").Range("z_BackupScriptText").Value
'replace the text "placeholder" with this workbook's actual full path/name:
strScriptText = Replace(strScriptText, "placeholder", ThisWorkbook.FullName)
'fire up FSO:
Set fso = CreateObject("scripting.filesystemobject")
'determine the new VBS file's path
strScriptPath = Environ("AppData") & "\Backup_" & Format(Now, "yymmddhhmmss") & ".vbs"
'create our textstream object:
Set ts = fso.createtextfile(strScriptPath)
'write our script into it
ts.write strScriptText
'save and close it
ts.Close 'RIGHT HERE THE FILE DISAPPEARS FROM THE FOLDER ***********
'GO:
Shell "wscript " & strScriptPath, vbNormalFocus
End Sub
It does look like an antivirus thing...
If the issue is just the vbs extension though, you can use something like this:
Sub tester()
Dim ts As Object, fso As Object, strScriptText As String, strScriptPath As String
Set fso = CreateObject("scripting.filesystemobject")
strScriptPath = Environ("AppData") & "\Backup_" & Format(Now, "yymmddhhmmss") & ".txt"
Set ts = fso.createtextfile(strScriptPath)
ts.write "Msgbox ""Hello"""
ts.Close
'need to specify the script engine to use
Shell "wscript.exe /E:vbscript """ & strScriptPath & """ ", vbNormalFocus
End Sub

copyfile ini to txt: permission-denied

I just want to copy the Content of a ini-File into a txt-file. But it tells me, that permission is denied.
The source file is closed
the Ini-file "Aly_complete.ini" was previously executed in the code via "java -jar"
As you see, I already tried another file, which wasn't used by the code before
Here is the code
Sub Kopieren_Ini(strPathQuelle As String, strPathErg As String)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Dim Quelle As String
Dim Ziel As String
If Sheets(1).TxtBoxIni.Text <> "" Then
Quelle = Sheets(1).TxtBoxIni.Text
Else
Quelle = strPathQuelle & "Aly_MitDatum.ini"
'Quelle = strPathQuelle & "Aly_complete.ini"
End If
Set oFile = fso.CreateTextFile(strPathErg & "\" & "Config_Test.txt")
Ziel = strPathErg & "\" & "Config_Test.txt"
FileSystem.FileCopy Quelle, Ziel
Thanks in advance for your help
Sounds like the .ini is being used by another application or process. What else is running? Does this still occur after you reboot? ( Source: my comment ☺)
Your code is incomplete (it doesn't End) so I can't say for sure, but I bet your issue is same common mistake that [imho] is the culprit in almost every complaint of Excel crashes caused by VBA code...
It's just like parenta are always telling their children:
The file is Open (and locked and taking up memory) until you .Close it.
Objects that are opened need to be closed & cleared.
Try adding these 3 lines to the end of your code (or where ever you're finished using the objects):
oFile.Close
Set oFile = Nothing
Set fso = Nothing
...then save your work, reboot, and try it again.
More Information:
Stack Overflow : Is there a need to set Objects to Nothing inside VBA Functions?
MSDN : FileSystemObject Object
MSDN : CreateTextFile Method
MSDN : Close Method (FileSystemObject)
EDIT: "Copy & Rename"
If you simply need to copy a file (and rename the copy at the same time), use this:
Option Explicit
Sub copyFile()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.copyFile "c:\sourcePath\sourceFile.ini", "c:\destinationPath\destFile.txt"
Set fso = Nothing
End Sub
More More Information:
Rob de Bruin : Copying & Moving Files with VBA
Excel Trick : FileSystemObject in VBA – Explained
MSDN : CopyFile Method

VBA Excel SSO to SAP / runtime error 70 "access denied"

I spend hours finding the problem.
I want to start the SAP Logonpad with the ini file, that works fine.
Then after binding to the scripting object I want to open the connection to a specific System with connection = SapGui.OpenConnection("SID", True)
but always get runtime error 70 access denied.
I followed what others seem to do with vbs, for certain resons I can't do it with vbs and have to go with vba, so maybe there might be some difference that makes it fail?
Any advice would be highly appreciated.
Private Sub CommandButton1_Click()
Dim SapGui As Object
Dim saplogon As Object
Dim connection 'As Object
Set SapGui = GetObject("SAPGUI")
Dim Wshshell As Object
Set Wshshell = CreateObject("Wscript.Shell")
Wshshell.Run Chr(34) & ("C:\Program Files\SAPPC\FrontEnd\SAPgui
\saplogon.exe") & Chr(34) & " " & "/INI_FILE" & "=" & Chr(34) &
"\\longpathtoini\appl\Sap\saplogon\int\saplogon.ini" & Chr(34)
Do Until Wshshell.AppActivate("SAP Logon")
Application.Wait Now + TimeValue("0:00:01")
Loop
Set Wshell = Nothing
Set saplogon = SapGui.GetScriptingEngine
connection = SapGui.OpenConnection("SID", True)
Set SapGui = Nothing
Set saplogon = Nothing
Set connection = Nothing
End Sub
Check whether user scripting is allowed for the particular system (transaction RZ11, parameter sapgui/user_scripting). Also be aware that for some versions, you'll apparently need to specify the SAP Logon entry text instead of the SID.
Thanks to vwegert.
I surely knew about scripting needs to be enabled on the servers.
Which is, but at the moment I read his answer I remembered that in my SAP GUI settings the checkbox for "Warn if a script tries to connect" was enabled.
Disabeling that options did lead to success.
The above code works perfectly.

Charts template folder

I've developed a superuseful addon which recreates source data for charts "disconnected" from Excel. So I .SaveChartTemplate then ApplyChartTemplate to a new chart, and need to delete temp. template.
Don't know how to get chart template folder. I assume that it's Environ("AppData") & "\Microsoft\Шаблоны\Charts\" but it's obvious that it works only with russian locale.
After analyzing registry keys, i've come to realize that templates folder name can be found in HKCU\Software\Microsoft\Office\<OFFICE VERSION>\Common\General\Templates
Assuming the above a possible solution is
Function chartTemplatesFolder() As String
On Error GoTo er:
Dim templatesFolder As String
templatesFolder = CreateObject("WScript.Shell").RegRead( _
"HKCU\Software\Microsoft\Office\" & Application.Version & "\Common\General\Templates")
chartTemplatesFolder = Environ("AppData") & "\Microsoft\" & templatesFolder & "\Charts\"
Exit Function
er:
End Function

Removing internal link to Word-templates via VBA

I'm trying to create a small VB-application that removes the internal link in Word Documents, to their templates.
I have found this guide
http://word.tips.net/Pages/T001437_Batch_Template_Changes.html
and am trying to modify it, to use with VBA instead of Macro programming inside of Office.
However, I'm getting stuck on how to get the Document.Open to work. Any help is appreciated.
This is supposed to run as a free-standing application, and not runt from within Word.
I'm looking for a way to perform what the Macro does, but not from within Word.
There are two pieces of bad news to give here.
1) A document has to have a template. You cannot remove it, only change it to something else.
2) Changing a template does nothing anyway. See this page.
I am wonder if the problem with the Open method is that you are trying to open ".doc" extension files, not the modern ".docx" extension files. The VBA subroutine you linked to only does ".doc" files. This VBA code does both:
Function StringEndsWith( _
ByVal strValue As String, _
CheckFor As String) As Boolean
Dim sCompare As String
Dim lLen As Long
lLen = Len(CheckFor)
If lLen > Len(strValue) Then Exit Function
sCompare = Right(strValue, lLen)
StringEndsWith = StrComp(sCompare, CheckFor, vbTextCompare) = 0
End Function
Sub ChangeTemplates()
Dim strDocPath As String
Dim strTemplateB As String
Dim strCurDoc As String
Dim docCurDoc As Document
' set document folder path and template strings
strDocPath = "C:\tmp\"
' get first doc - only time need to provide file spec
strCurDoc = Dir(strDocPath & "*.doc*")
' ready to loop (for as long as file found)
Do While strCurDoc <> ""
If (StringEndsWith(strCurDoc, ".doc") Or StringEndsWith(strCurDoc, ".docx")) Then
' open file
Set docCurDoc = Documents.Open(FileName:=strDocPath & strCurDoc)
' change the template back to Normal
docCurDoc.AttachedTemplate = ""
' save and close
docCurDoc.Close wdSaveChanges
End If
' get next file name
strCurDoc = Dir
Loop
MsgBox "Finished"
End Sub
long time between answers but may be useful to others. If you have access to the VBE of the Word document [Alt F11], and you want to remove the reference then go to "Tools/References" [top menu] and deselect it from the list of reference files. I had a similar issue where template no longer existed, but it was still being 'referenced' in the Project window, so I did the above.