Permission Denied accessing csv file with VBS - variables

I'm trying to create a line in VBS that will create a file path with the file name as a variable, but I'm getting a Permission Denied error.
This is what I have so far:
filename = WScript.Arguments.unnamed(0) 'this value is transfered from a batch file.
Const ForReading = 1, ForWriting = 2, ForAppending = 8, CreateIfNeeded = true
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.Load ("C:\Users\c1921\Ayla_Data\XMLFile.xml")
Set colNodes = xmlDoc.SelectNodes _
("/properties/property/(name)")
For Each objNode In colNodes
strSource = "C:\Users\c1921\Ayla_Data\AylaDatapoints\" & filename & ".csv"
Dim fso, f
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set f = fso.OpenTextFile(strSource, 2)
I've also added a msgbox(filename) line to see what value I get and it is the correct value.
I've also tried something like this to see if it would help and it doesn't work either:
Set f = fso.OpenTextFile("C:\Users\c1921\Ayla_Data\AylaDatapoints\AC000N000004593.csv", 2)
This should be easy I don't know where I'm going wrong. Any help finding the right direction would be greatly appreciated.
I've also tried something like this (among other variations) if it's relevant:
Set f = fso.OpenTextFile("C:\Users\c1921\Ayla_Data\AylaDatapoints\" & Chr(34) & filename & Chr(34) & " " & ".csv", 2) & Chr(34)
Edit:
Tried making the file in VBs with this code:
strSource = "C:\Users\c1921\Ayla_Data\AylaDatapoints\" & filename & ".csv"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.CreateTextFile(strSource, _
ForWriting, True)
objLogFile.Writeline
I still get Permission Denied run time error. The file is created but this is the only thing written in it:
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

If your .bat file re-directs the (StdOut) output of curltest.vbs into a .csv file then it makes no sense to create (or write to) the .csv in the .vbs. Instead you should WScript.Echo the info you want to appear in the .csv.
In addition, you need to get rid of the logo - either by starting the .vbs with //NoLogo or 'burning' the //NoLogo switch into the user's c/wscript by using the //S option.
Evidence:
copy con curltest.vbs
WScript.Echo "WScript.Echoed into whatever.csv"
^Z
cscript //NoLogo curltest.vbs >whatever.csv
type whatever.csv
WScript.Echoed into whatever.csv

Related

VBA FileExists and Sharepoint

I'm running into issues trying to pull info from files stored in Sharepoint.
Namely, FileExists isn't working and Overwrite file doesn't seem to be working either.
There was a discussion here, but few answers -> posting this question again in hopes some things have changed
My code runs like this:
strFileExists = Dir(Filepath & Filename)
And returns: File path not found -> I checked the path and even opened a file and recorded the macro to make sure it was the same file path without issue, but it appears DIR() is the issue.
The business dept I'm working with is entirely switching over to Sharepoint so hoping there's a straightforward solution without setting up network shares or doing C/personal/OneDrive things
You can navigate and look for files on OneDrive like this
Sub check_File_Exists()
Dim path As String
Dim strType As String
Dim file As Variant
Dim yourFile As String
'replace uname with your user name
path = "C:\Users\uname\OneDrive\"
strType = "*txt"
yourFile = "test.txt"
file = Dir(path & strType)
Do While (file <> "")
If file = yourFile Then
Debug.Print ("File: " & file & " found!")
Exit Do
End If
file = Dir
Loop
End Sub
Hope it helps

Is there an argument for copyfile that will change the hidden property?

I have a database that writes data into a copied excel template. The template is hidden to keep the end user from tampering with it, however the final result is also hidden. Is there a way to change the hidden property when saving the new file?
Currently, the db copies the template and renames it.
fso.CopyFile "C:\Upload\Rebate_Upload_Files\Standard Form (Template)
protected.xlsx", "C:\Upload\Rebate_Upload_Files\Rebate Contract " &
Contract_Number & " " & Date$ & ".xlsx"
After that, it transfers the appropriate table and saves the file.
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml,
"export_table", "C:\Upload\Rebate_Upload_Files\Rebate Contract " &
Contract_Number & " " & Date$ & ".xlsx", False, "A12:L65000"
The process works fine, except that the final file is also hidden and I'd like it to be a normal file.
Thanks
Not for CopyFile-which is a FileSystemObject method, but there is one for a File object. We'll just update it after the copy is complete.
For simplicity i've replaced your file output path to a string variable.
originalFileName = "yourStartingFile"
copyFileName = "yourCopiedFile"
set fso.CopyFile OriginalFileName, CopyFileName
--after copying, get file that was copied
--set attributes value of file to 0. 0 = Normal, 2 = Hidden
f = fso.GetFile(copyFileName)
f.attributes = 0
More reading for additional details.
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/file-object
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/attributes-property
Mike's code above worked, however there was a few more steps involved for me so I wanted to provide the full code for anyone stumbling upon this.
First, in order to use FileSystemObject, you need to enable it in your VBA Editor by going to Tools->References and enabling "Microsoft Scripting Runtime". Then, using the code below, you can copy a hidden file and set the new file (via f.Attributes) to not be hidden:
' SourceFile is the full path name to my original file
' FileNAme is the full path name to my new file
Dim fso As Scripting.FileSystemObject
Dim f As File
Set fso = New Scripting.FileSystemObject
Call fso.CopyFile(SourceFile, FileName, False) ' Set to true to overwrite
Set f = fso.GetFile(FileName)
f.Attributes = 0

VBA open a csv file with unknow file name

I have got a rather simple question as i think but i couldnt find out it myself.
I want to open a csv File in a defined binder but with an unknow filename. I would asume that it should work with simply "path/*.csv" however it is not :( The errormessage says "Wrong Filename". Do i need to use something else in VBA.
path = ActiveWorkbook.path & "\input\"
Open path & "*.csv" For Binary As #1
The above code does not work for me :( The CSV is called xyz.csv
path = ActiveWorkbook.path & "\input\"
Open path & "xyz.csv" For Binary As #1
The code above is working however i have fix added the csv filename, which in this case is xyz.
Somebudy knows how to get that thing to work?
Cheers and thx for your time
Marc
Dim path As String
Dim csvFiles As String
path = ActiveWorkbook.path & "\input\"
csvFiles = Dir(path & "*.csv")
Do While Len(csvFiles) > 0
Debug.Print csvFiles
csvFiles = Dir
Loop
You can use the Dir() Function to check the files in your folder if you don't know the filename.

Vb file exists script

I have this script but would like to enhance it that in the absence of the file on the C: copy the one from the R: Drive. Currently on check if file is there.
Currently this script will run on multiple files in a single folder \SCRIPTS.
As I repeat the statement for each of different file name (I do know the file names) A more economic way of checking all files in the the R:\SCRIPTS and comparing to the C:\SCRIPTS copying or overwriting file would be good if anyone has a snippet that might help
Const OverwriteExisting = TRUE
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLocalFile = objFSO.GetFile("C:\SCRIPT\SCRIPTTEXT.txt")
dtmLocalDate = objLocalFile.DateLastModified
Set objServerFile = objFSO.GetFile("R:\SCRIPT\SCRIPTTEXT.txt")
dtmServerDate = objServerFile.DateLastModified
If dtmLocalDate < dtmServerDate Then
objFSO.CopyFile objServerFile.Path, objLocalFile.Path, OverwriteExisting
End If
using System.IO;
Dim ServerFolder As New IO.DirectoryInfo("R:\SCRIPT")
Dim LocalFolder As New IO.DirectoryInfo("C:\SCRIPT")
For Each ServerFile In ServerFolder.GetFiles
If IO.File.Exists(LocalFolder.FullName & "\" & ServerFile.Name) Then
Dim LocalFile As New IO.FileInfo(LocalFolder.FullName & "\" & ServerFile.Name)
If ServerFile.LastWriteTime > LocalFile.LastWriteTime Then
IO.File.Copy(ServerFile.FullName, LocalFile.FullName, True)
End If
Else
IO.File.Copy(ServerFile.FullName, LocalFolder.FullName & "\" & ServerFile.Name)
End If
Next

Use a variable in file path in .vbs

Is it possible to usa variable in a path in .vbs. My basic situation is I have a vbs script that will often be run on a computer with one person logged in and run by an admin with a completely different user name (assume the file will be right clicked and "Run As").
The script edits an ini file that is located in the user directory for the person logged in. I know in batch I could simply insert the variable "C:\Users\%Logger%\AppData\Local\stat.ini" and the variable would be replaced. But I can't do this in .vbs. My script thus far. Or look at the bulk of it in an answer here.
Dim blnRes: blnRes = 0
Dim strOld, strNew, logger
strOld = "frogg"
strNew = "frog"
logger = Inputbox("What is your Domain ID exactly as entered when you log into this machine?","Domain ID")
On Error Resume Next
Call update("C:\Users\logger\AppData\Local\stat.ini", strOld, strNew)
blnRes = blnRes Or (Err.Number = 0): Err.Clear
Is there some way I can flag logger as a variable, or is there an easier way to do this?
I guess you meant a script variable. Try this:
logger = Inputbox("What is ID?","Domain ID")
Call update("C:\Users\"& logger &"\AppData\Local\stat.ini", strOld, strNew)
You can use command line arguments with vbs. See the following technet site:
http://technet.microsoft.com/en-us/library/ee156618.aspx
using the example vbs at the bottom, you can have Ping.vbs reply based on the computer name entered after the script name when its called (C:\scripts\Ping.vbs Hostname)
Here's more info on WScript.Aurguments
https://www.google.com/search?q=WScript.Arguments&sourceid=ie7&rls=com.microsoft:en-us:IE-Address&ie=&oe=
'Ping.vbs:
Dim arArguments, strArgument
Set arArguments = WScript.Arguments
WScript.Echo WScript.Arguments.Count
For Each strArgument in arArguments
If Ping(strArgument) Then
WScript.Echo strArgument & " is available."
Else
WScript.Echo strArgument & " is not available."
End If
Next
Function Ping( myHostName )
Dim colPingResults, objPingResult, strQuery
strQuery = "SELECT * FROM Win32_PingStatus WHERE Address = '" & myHostName & "'"
Set colPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery )
For Each objPingResult In colPingResults
If Not IsObject( objPingResult ) Then
Ping = False
ElseIf objPingResult.StatusCode = 0 Then
Ping = True
Else
Ping = False
End If
Next
Set colPingResults = Nothing
End Function
If I understand what you're after correctly, you're either going to need to do a string concatenation where you build a string like "string part 1" & logger & "string part 2" or use the replace function to replace %Logger% (e.g. Replace(templateString, "%Logger%", logger)) with your logger variable. There's not a direct equivalent to the %1 sort of format used in batch files.
This worked for me:
Dim fs, ws, Path
Set ws = CreateObject( "WScript.Shell" )
Path = ws.ExpandEnvironmentStrings( "%UserProfile%\testfile.txt" )
ws = Nothing
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile (Path, True)
f.WriteLine("This is a test")
f.Close()
f = Nothing
Don't assume "C:\Users" will be valid on every system. There are times when you may want to use a different location for user profiles. I also looked at the %AppData% environment variable, but in my case that pointed to AppData\Roaming, and you want AppData\Local.