I found a problem with the VBA Locals Window while debuggin a macro in Excel 2013. I used the Locals Window to track the value of a string.
If the string exceed a certain length (about 100 caracters) it is not possible to copy it out of the Locals Window to examine it somewhere else (eg. in notepad++).
Is there a way to access the full content of a string variable at runtime ?
You can also dump the output to a txt file.
"response" is the variable to output in the below example.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile("C:\Development\DebugOutput.txt")
oFile.WriteLine response
oFile.Close
Set fso = Nothing
Set oFile = Nothing
Related
I'm currently working on developing a macro that will input various forms into an access database.
Due to the nature of the beast of this program, I've had to split my main program into two sub programs and call them, but I need to use getobject to call a file path twice now.
I use getobject to open a file, and then use myrec.fields(~column name~) = xlsht.cells(1, "a") to populate various column values. I'm unsure if there are other "efficient" ways to accomplish this.
I was wondering if it is possible to use a variable in place of the filepath with the GetObject command, instead of needing to manually replace the file path in the code.
I've tested a fair amount of different code, including the path, class functionality but I don't think I understand VBA enough to truly make the best use of that.
I can make it work using this
Dim XL As Variant
Dim XLApp As Variant
Dim XLsht As Variant
Dim XLwrkbk As Variant
Set XL = CreateObject("Excel.Application")
Set XLwrkbk = GetObject(~file path~)
Set XLsht = XLwrkbk.Worksheets(1)
Set MyRec = CurrentDb.OpenRecordset("database name")
Ideally I would like it to be
Dim filename As String
Dim XL As Variant
Dim XLApp As Variant
Dim XLsht As Variant
Dim XLwrkbk As Variant
filename = " ~insert file path~ "
Set XL = CreateObject("Excel.Application")
Set XLwrkbk = GetObject(filename)
Set XLsht = XLwrkbk.Worksheets(1)
Set MyRec = CurrentDb.OpenRecordset("database name")
I receive a run time error
Run-time error '5':
Invalid procedure call or argument.
Try something like this:
Dim XL As New Excel.Application, Filename As String
Filename = "~ your file ~"
XL.Workbooks.Open (Filename)
myrec.fields(~column name~) = XL.Worksheets(1).Range("A1").value
In MS Outlook (2016) I am working on a VBA procedure to more quickly archive certain, individually selected e-mails into certain folders in my e-mail archive.
I have a procedure that does the trick when I address the target folder manually:
'[...]
Dim MoveToFolder As Outlook.MAPIFolder
'[...]
Set MoveToFolder = ns.Folders("Archive").Folders("Projekte-Archiv").Folders("P03_NetRef")
'[...]
With this the procedure knows what folder to move pre-selected e-mail to.
Now my problem:
I am trying to set the "MoveToFolder" folder object through a string variable giving it all the necessary data.
Why do I want to do this: Handing over the folder data as a string variable would allow me to use the same procedure for as many folders in as many hierarchy levels I want.
Here is what I came up with, using the CType function:
'[...]
Dim MoveToFolder As Outlook.MAPIFolder
'[...]
Set MoveToFolder = CType("ns.Folders(""Archive"").Folders(""Projekte-Archiv"").Folders(""P03_NetRef"")", Outlook.MAPIFolder)
'[...]
(The idea is of course in a next step to insert the string through a variable, not in plain writing like the example.)
This does not work. The object type 'Outlook.MAPIFolder' results in an error on compiling ("method or data object not found").
Later insight
As I understood later on, the CType() function is not available in VBA (as opposed to VB.net).
Untested:
Set MoveToFolder = GetFolder(ns, "Archive|Projekte-Archiv|P03_NetRef")
A function to parse the path:
Function GetFolder(root, fpath)
Dim f As Object
Dim arr, i
arr = Split(fpath, "|")
For i = 0 To UBound(arr)
If i = 0 Then
Set f = root.Folders(arr(i))
Else
Set f = f.Folders(arr(i))
End If
Next i
Set GetFolder = f
End Function
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
i'm coding a macro for word and excel. The output are generated files that should be saved.
Since those files already exist and are write protected, I somehow have to remove the protection. I found a unprotect function in excel but it doesn't really work.
I also didn't find any command for unprotecting via cmd o0
I thought about deleting the files before saving the new ones.
But I'd like to find a solution for unprotecting.
try attrib command in cmd to change file attributes
attrib *.xls -r will help you to remove readonly attribute.
Here's a way to remove the read-only attribute from VBA using the FileSystemObject:
Sub RemoveReadOnly(filePath As String)
Dim FSO As FileSystemObject
Dim f As Scripting.File
Set FSO = New FileSystemObject
Set f = FSO.GetFile(filePath)
If fil.Attributes And ReadOnly Then 'It's read-only. Remove that attribute.
fil.Attributes = fil.Attributes - ReadOnly
End If
End Sub
Usage:
RemoveReadOnly "C:\mydir\myReadOnlyFile.dat"
More info: http://msdn.microsoft.com/en-us/library/5tx15443%28v=vs.85%29.aspx
Note: The above requires setting a reference as follows: Tools > References... > set checkmark next to Microsoft Scripting Runtime.
If you don't want to set a reference, then use late binding instead:
Sub RemoveReadOnly(filePath As String)
Dim FSO As Object
Dim fil As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set fil = FSO.GetFile(filePath)
If fil.Attributes And 1 Then '1 = ReadOnly
fil.Attributes = fil.Attributes - 1
End If
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()