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
Related
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
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
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.
Let's say I have 100 users and I need to add several network locations for each user. They cannot be network drives (e.g. Q:) as some users already have more than 26 drives mapped.
I was hoping to do this using either a batch file or a VB script. I've managed to get it working using a VB script by adding network shortcuts but this isn't the solution the users need.
I've been searching and can't find anything related specifically to Network Locations.
I'm open to trying other methods.
EDITED to properly answer the question; the original answer, that creates a shortcut in Network Locations, is kept at the end.
After some testing, a network location is a read-only folder located in the %AppData%\Microsoft\Windows\Network Shortcuts folder, with two files inside: desktop.ini with a precise content (see in code) and a target.lnk shortcut to the target.
Option Explicit
Function CreateNetworkLocation( networkLocationName, networkLocationTarget )
Const ssfNETHOOD = &H13&
Const fsATTRIBUTES_READONLY = 1
Const fsATTRIBUTES_HIDDEN = 2
Const fsATTRIBUTES_SYSTEM = 4
CreateNetworkLocation = False
' Instantiate needed components
Dim fso, shell, shellApplication
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set shell = WScript.CreateObject("WScript.Shell")
Set shellApplication = WScript.CreateObject("Shell.Application")
' Locate where NetworkLocations are stored
Dim nethoodFolderPath, networkLocationFolder, networkLocationFolderPath
nethoodFolderPath = shellApplication.Namespace( ssfNETHOOD ).Self.Path
' Create the folder for our NetworkLocation and set its attributes
networkLocationFolderPath = fso.BuildPath( nethoodFolderPath, networkLocationName )
If fso.FolderExists( networkLocationFolderPath ) Then
Exit Function
End If
Set networkLocationFolder = fso.CreateFolder( networkLocationFolderPath )
networkLocationFolder.Attributes = fsATTRIBUTES_READONLY
' Write the desktop.ini inside our NetworkLocation folder and change its attributes
Dim desktopINIFilePath
desktopINIFilePath = fso.BuildPath( networkLocationFolderPath, "desktop.ini" )
With fso.CreateTextFile(desktopINIFilePath)
.Write "[.ShellClassInfo]" & vbCrlf & _
"CLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}" & vbCrlf & _
"Flags=2" & vbCrlf
.Close
End With
With fso.GetFile( desktopINIFilePath )
.Attributes = fsATTRIBUTES_HIDDEN + fsATTRIBUTES_SYSTEM
End With
' Create the shortcut to the target of our NetworkLocation
Dim targetLink
targetLink = fso.BuildPath( networkLocationFolderPath, "target.lnk" )
With shell.CreateShortcut( targetLink )
.TargetPath = networkLocationTarget
.Save
End With
' Done
CreateNetworkLocation = True
End Function
CreateNetworkLocation "Tests", "\\192.168.1.2\c$"
Tested in Windows 7.
Original answer - Just in case someone finds it useful.
All you need to do is to create a shortcut in the folder:
%AppData%\Microsoft\Windows\Network Shortcuts
Just a VBScript sample (as indicated in the question, not sure if the tags points to another needs):
Option Explicit
Const ssfNETHOOD = &H13&
Dim fso, shell, shellApplication
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set shell = WScript.CreateObject("WSCript.Shell")
Set shellApplication = WScript.CreateObject("Shell.Application")
Dim networkLocationsFolder
networkLocationsFolder = shellApplication.Namespace( ssfNETHOOD ).Self.Path
With shell.CreateShortcut(fso.BuildPath( networkLocationsFolder, "Test PC.lnk" ))
.TargetPath = "\\192.168.1.10\c$"
.WindowStyle = 1
.IconLocation = "shell32.dll, 9"
.Description = "Access to Test computer drive"
.WorkingDirectory = "\\192.168.1.10\c$"
.Save
End With
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