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
Related
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
I am using below code to get the created date of a workbook.
Dim mFile As String
mFile = "C:\User\User.Name\Test\Test.xlsx"
Debug.Print CreateObject("Scripting.FileSystemObject").GetFile(mFile).DateCreated
However to my surprise, this returns the date when the file is created in the directory. If you copy the file to another folder, above will return that time and date it was copied (created).
To actually get the original created date, I tried using BuiltinDocumentProperties method. Something like below:
Dim wb As Workbook
Set wb = Workbooks.Open(mfile) '/* same string as above */
Debug.Print wb.BuiltinDocumentProperties("Creation Date")
Above does return the original date the file was actually created.
Now, I have hundreds of file sitting in a directory that I need to get the original creation date. I can certainly use above and look over the files, but opening and closing all of it from a shared drive takes some time. So I was wondering, if I can get the BuiltinDocumentProperties without opening the file(s) like using the first code above which is a lot faster and easier to manage.
If you somebody can point me to a possible solution, that would be great.
Try something like this. The key is the special DSO object.
Imports Scripting
Private Sub ReadProperties()
Dim pathName As String = "C:\yourpathnamehere"
Dim Fso As FileSystemObject = New Scripting.FileSystemObject
Dim fldr As Folder = Fso.GetFolder(pathName)
Dim objFile As Object = CreateObject("DSOFile.OleDocumentProperties")
Dim ResValue As String = Nothing
For Each f In fldr.Files
Try
objFile.Open(f)
ResValue = objFile.SummaryProperties.DateCreated
' Do stuff here
objFile.Close
Catch ex As Exception
'TextBox1.Text = ex.Message
End Try
Application.DoEvents()
Next
End Sub
I have some VBA code in Excel 2007 which creates, fills, then closes a Textstream file object (abbreviated snippet below).
Set CSV = FSO.CreateTextFile(strPathOut & Application.PathSeparator & strFileOut)
'Fill the file
CSV.Close
The code works perfectly, including the CSV.Close instruction, however if I then try to delete or modify the file (e.g. in Windows Explorer or Notepad) the system claims Excel still has the file open. Seemingly the only way to release it is to close Excel itself.
I've checked that CSV.Close is doing what it's supposed to from the VBA side; it's not causing a runtime error, and certainly the file is no longer available to be written to after that instruction.
My project is early bound to the Microsoft Scripting Runtime, scrrun.dll. I've tried removing that reference but I get the same result.
This is not a showstopper for the project, but it's a PITA during development. Anybody know what's going on?
Try this simple example - the file is available for editing through e.g. Notepad, after the code has run:
Option Explicit
Sub Test()
Dim objFSO As New FileSystemObject
Dim objStream As TextStream
Dim i As Integer
Set objStream = objFSO.CreateTextFile("D:\temp.txt")
With objStream
For i = 1 To 10
.WriteLine CStr(i)
Next i
.Close
End With
Set objStream = Nothing
Set objFSO = Nothing
End Sub
This seems so simple and I've had it working multiple times, but something keeps breaking between my Dir call (to iterate through a directory) and opening the current file. Here's the pertinent code:
SourceLoc = "C:\ExcelWIP\TestSource\"
SourceCurrentFile = Dir(SourceLoc)
'Start looping through directory
While (SourceCurrentFile <> "")
Application.Workbooks.Open (SourceCurrentFile)
What I get with this is a file access error as the Application.Workbooks.Open is trying to open "C:\ExcelWIP\TestSource\\FILENAME" (note extra slash)
However when I take the final slash out of SourceLoc, the results of Dir(SourceLoc) are "" (it doesn't search the directory).
The frustrating thing is that as I've edited the sub in other ways, the functionality of this code has come and gone. I've had it work as-is, and I've had taking the '/' out of the directory path make it work, and at the moment, I just can't get these to work right together.
I've scoured online help and ms articles but nothing seems to point to a reason why this would keep going up and down (without being edited except for when it stops working) and why the format of the directory path will sometimes work with the final '/' and sometimes without.
any ideas?
This would open all .xlxs files in that directory son.
Sub OpenFiles()
Dim SourceCurrentFile As String
Dim FileExtension as String: FileExtension = "*.xlxs"
SourceLoc = "C:\ExcelWIP\TestSource\"
SourceCurrentFile = Dir(SourceLoc)
SourceCurrentFile = Dir()
'Start looping through directory
Do While (SourceCurrentFile <> "")
Application.Workbooks.Open (SourceLoc &"\"& SourceCurrentFile)
SourceCurrentFile = Dir(FileExtension)
Loop
End Sub
JLILI Aman hit on the answer which was to take the results of Dir() as a string. Using that combined with the path on Application.Open allows for stable behaviors from the code.
New Code:
Dim SourceLoc as String
Dim SourceCurrentFile as String
SourceLoc = "C:\ExcelWIP\TestSource\"
SourceCurrentFile = Dir(SourceLoc)
'Start looping through directory
While (SourceCurrentFile <> "")
Application.Workbooks.Open (SourceLoc & "/" & SourceCurrentFile)
I didn't include the recommended file extension because I'm dealing with xls, xlsx, and xlsm files all in one directory. This code opens all of them.
Warning - this code will set current file to each file in the directory including non-excel files. In my case, I'm only dealing with excel files so that's not a problem.
As to why this happens, it does not appear that Application.Open will accept the full object results of Dir(), so the return of Dir() needs to be a String. I didn't dig deeper into the why of it beyond that.
Consider using VBA's FileSystemObject which includes the folder and file property:
Sub xlFilesOpen()
Dim strPath As String
Dim objFSO As Object, objFolder As Object, xlFile As Object
strPath = "C:\ExcelWIP\TestSource"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strPath)
For Each xlFile In objFolder.Files
If Right(xlFile, 4) = "xlsx" Or Right(xlFile, 3) = "xls" Then
Application.Workbooks.Open (xlFile)
End If
Next xlFile
Set objFSO = Nothing
Set objFolder = Nothing
End Sub
I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file.
I want to write the c codes which are going to be printed in that .txt file.
What is the command to create a .txt file using VBA, and how do I write to it
Use FSO to create the file and write to it.
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test"
oFile.Close
Set fso = Nothing
Set oFile = Nothing
See the documentation here:
http://technet.microsoft.com/en-us/library/ee198742.aspx
http://technet.microsoft.com/en-us/library/ee198716.aspx
Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1
More Information:
Microsoft Docs : Open statement
Microsoft Docs : Print # statement
Microsoft Docs : Close statement
wellsr.com : VBA write to text file with Print Statement
Office Support : Workbook.Path property
To elaborate on Ben's answer:
If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.
Here is a complete example module:
Option Explicit
' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()
Dim filePath As String
filePath = "C:\temp\MyTestFile.txt"
' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
' (Intellisense) work, which helps you avoid typos and lets you discover other useful
' methods of the FileSystemObject
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim fileStream As TextStream
' Here the actual file is created and opened for write access
Set fileStream = fso.CreateTextFile(filePath)
' Write something to the file
fileStream.WriteLine "something"
' Close it, so it is not locked anymore
fileStream.Close
' Here is another great method of the FileSystemObject that checks if a file exists
If fso.FileExists(filePath) Then
MsgBox "Yay! The file was created! :D"
End If
' Explicitly setting objects to Nothing should not be necessary in most cases, but if
' you're writing macros for Microsoft Access, you may want to uncomment the following
' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
'Set fileStream = Nothing
'Set fso = Nothing
End Sub
an easy way with out much redundancy.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
Fileout.Write "your string goes here"
Fileout.Close
Dim SaveVar As Object
Sub Main()
Console.WriteLine("Enter Text")
Console.WriteLine("")
SaveVar = Console.ReadLine
My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)
Console.WriteLine("")
Console.WriteLine("File Saved")
Console.WriteLine("")
Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
Console.ReadLine()
End Sub()