FileSystemObject FileExists works on one computer but not another - vba

In Excel 2010 VBA, I'm using the FileExists property of the FileSystemObject to check whether a file exists. On my computer it works fine. But on another Excel 2010 computer, it reports that the file is not there when in fact we see in Windows Explorer that the file is there. In both cases, the file being checked is on the local hard drive.
I'm checking for the file right after using Shell to unzip the file. I use DoEvents after the unzip. The file is being extracted to the same folder that the zip file is in.
Here's the code:
Dim oShell As Object, oZippedFile As Object, oUnzipTargetFolder As Object
Dim FSO As Object, oFile As Object, oFolder As Object
Dim strZipfileFullpath As Variant, strTargetFolderpath As Variant, strTargetFullpath As Variant 'NOT AS STRINGS!! (Shell error if strings)
Dim bFileCheckFsoFileExist As Boolean
Set oShell = CreateObject("shell.application")
Set FSO = CreateObject("scripting.filesystemobject")
strZipfileFullpath = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
Set oFile = FSO.GetFile(strZipfileFullpath)
Set oFolder = oFile.ParentFolder
strTargetFolderpath = oFolder.Path & Application.PathSeparator
strTargetFullpath = strTargetFolderpath & oShell.Namespace(strZipfileFullpath).Items.Item(0).Name
oShell.Namespace(strTargetFolderpath).CopyHere oShell.Namespace(strZipfileFullpath).Items.Item(0) 'this zip has only one file.
DoEvents
bFileCheckFsoFileExist = FSO.FileExists(strTargetFullpath)
Any ideas why this works fine on one computer, but on another computer reports that the file is not there even though it we see that it clearly is?
UPDATE:
I thought I'd add this note in case it may be helpful for others running into the same snag.
The basic underlying issue was that when using Shell to extract a zipped file, the Name property of the zipped file object does not include the extension If Windows Explorer is hiding extensions and the file has a registered extension. For example:
Dim strGofnZipfileFullpath As Variant
Dim oShell As Object, oShellZipfile As Object, oShellZippedFileInZipfile As Object
Dim strShellZippedFileInZipfileFilename As Variant 'NOT AS STRINGS!! (Shell error if strings)
strGofnZipfileFullpath = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
Set oShell = CreateObject("shell.application")
Set oShellZipfile = oShell.Namespace(strGofnZipfileFullpath)
Set oShellZippedFileInZipfile = oShellZipfile.Items.Item(0) 'assumes only 1 file in zip.
strShellZippedFileInZipfileFilename = oShellZippedFileInZipfile.Name
If Windows Explorer is set to hide extensions and the zipped file has a registered extension, strShellZippedFileInZipfileFilename does not include the extension.
However, the zipped file object (oShellZippedFileInZipfile) also has a Path property which does include the extension. So you can get the filename including extension like this:
strShellZippedFileInZipfileFilename = Right(oShellZippedFileInZipfile.Path, InStr(StrReverse(oShellZippedFileInZipfile.Path), Application.PathSeparator) - 1)

One thing to keep in mind is the folder options within Windows explorer. This may not help you in this case, but I have had a number of fso interactions that have a huge issue with how files are displayed in Windows Explorer. Something as simple as your system is displaying the file extension, and the other is not, can sometimes be the culprit in looking for files.

Related

VBA replace file in open document (other than word/excel)

We use PcSchematic for our electric drawings. And we use PDM to manage the revision. I would like to write into the pcschematic file with the current revision from PDM.
A pcSchematic file can be opened with a notepad. so what I would like to do is:
Dim filePath as string = "C:\16368.04.PRO"
Open file with notepad Process.Start("notepad", filePath)
find and replace a line
save
close
I have tried this:
Dim objFSO
Dim objTS
objFSO = CreateObject("Scripting.FileSystemObject")
objTS = objFSO.OpenTextFile(filePath, 2)
From this Text file in VBA: Open/Find Replace/SaveAs/Close File
but it only seems to work for .txt files
Can anyone point me in the right direction?

Use FileDialog To Select File Then Copy, Paste, Rename, Delete [duplicate]

This question already has answers here:
ms access browse for file and get file name and path
(3 answers)
Closed 2 years ago.
In Access (2016), I am trying to import various Excel files from vendors we use at my work. Their formats are all different, so I need to setup a specific saved import within Access for each one. I then want the users to be able to click the import button, and the excel file be imported to the database.
I initially used the Runsavedimportexport command, but that has a static file path and I don't fully understand transferspreadsheet to be able to use it.
My question is this, how can I use FileDialog to open the file selector, let my users select a file (probably from the desktop), then save that as a variable to run CopyFile. After CopyFile runs and pastes the copy, rename to a specific name, run runsavedimportexport then delete the file.
I have found all the various arguments for each code, but am struggling to tie it all together.
So far all I have managed to put together is
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
‘assuming you have added a reference to Microsoft Scripting Library for file system manipulation
‘assuming you have added a reference to Microsoft Office Object 16 library for file dialogs
‘assuming you have used the external data-tab to save some imports from a hidden file named c:\yourdirectory\importme.xlsx
‘assuming you also stored the names of those imports in an access tabled called QueryNames
Then create a form with a listbox and a button. Set the rowsource of the listbox to the QueryNames Table and set the listbox.multiselect to none.
Here is the code:
Private Sub cmdImportData_Click()
Dim fso As FileSystemObject
Dim filedialog As Office.filedialog
Dim filepath As String
dim targetpath as string: targetpath = c:\yourdirectory\importme.xlsx
Set fso = New FileSystemObject
Set filedialog = Application.filedialog(msoFileDialogFilePicker)
filedialog.AllowMultiSelect = False
If filedialog.Show = True Then
filepath = filedialog.SelectedItems(1)
fso.CopyFile filepath, targetpath, True
Dim FirstQueryID As Integer: FirstQueryID = 1 ''crude way to select between 2 stored queries
Dim SecondQueryID As Integer: SecondQueryID = 2
If listboxofQueryNames = FirstQueryID Then
DoCmd.RunSavedImportExport ("MyFirstSavedQuery")
fso.DeleteFile targetpath
End If
Else
DoCmd.RunSavedImportExport ("MySecondSavedQuery")
fso.DeleteFile targetpath
End If
End Sub
Helpful Links
https://learn.microsoft.com/en-us/office/vba/api/access.application.filedialog
Copy and paste a file through access vba

Convert multiple .xls files to .xlsx in ssis

I have a folder that receives multiple excel files in .xls format. I need to change the format type to .xlsx in order to load the excel data into SQLvia SSIS. I know how to rename the file using "File System Task" but that works for a specific file. but my file contains a file # and date as well that needs to stay same as source file, I only want the file type to change and the file move to a processed folder. Can anyone help me?
Source Path: C:\Documents\TestFolder
Source File: TestSegRpt_0001_2017_02_22.xls
Destination Path: C:\Documents\TestFolderProcessed
Destination File: TestSegRpt_0001_2017_02_22.xlsx
Hoping i understood your problem correctly.
I think below link will help.
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-mso_other/batch-convert-xls-to-xlsx/1d9b3d78-daf0-4014-8fb2-930aca6493b0
You have to add a Script Task, loop over files, and use a function like the following to create precessed directory and convert files (code in Vb.net):
Public Sub ConvertXlsToXlsx(ByVal strpath as string)
Dim strDirectory as string = System.IO.Path.GetDirectoryName(strpath) & "Processed"
If Not System.IO.Directory.Exists(strDirectory) Then System.IO.Directory.CreateDirectory(strDirectory)
Dim xl As New Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
xlWorkBook = xl.Workbooks.Open(strpath)
xlBook.SaveAs(strDirectory & "\" & System.IO.Path.GetFilename(strpath) & "x")
xl.Application.Workbooks.Close()
xl.Application.Quit()
End Sub
Your code will look like:
Public Sub Main
Dim strFolder as string = Dts.Variables.Item("FolderPath").Value
Dim strXlsFiles() as string = IO.Directory.GetFiles(strFolder,"*.xlsx",SearchOption.TopDirectoryOnly)
For each strFile as String in strXlsFiles
If strFile.EndsWith("xlsx") The Continue For
ConvertXlsToXlsx(strFile)
Next
End Sub
Reference:
https://social.msdn.microsoft.com/Forums/office/en-US/a73f846c-91ee-4dad-bd7b-c04d418d0561/convert-xls-into-xlsx?forum=exceldev

Writing GMAIL inbox html to file fails (VBA, Textstream)

I retrieved a HTML file that I want to save using a textstream object from FileSystemObjects and it produces an empty file.
When I use MsgBox to display the stream right before the write command it shows all the HTML code I want, but it doesn't write the code to the file. Any suggestions?
Dim FSO As FileSystemObject
Dim FSOFile As TextStream
Dim FilePath As String
FilePath = "C:\myhtml.html"
Set FSO = New FileSystemObject
Set FSOFile = FSO.OpenTextFile(FilePath, 2, True)
FSOFile.Write myContent ' String object holding the HTML textstring
FSOFile.Close
I basically am trying to export my gmail inbox folder which I want to use as an event listener (so I can tell another machine what it is supposed to do.) .
On your comments so far:
- riteLine does not make any difference
- OpenTextFile creates non-existing files and it also creates the file and writes any other string that I manually type in, s.a. FSOFile.WriteLine "Nothing works"
- For completeness: CreateTextFile also did not help.
Any likely problem of writing the HTML code using the FSO stream?
Try WriteLine instead of just Write.
See Example: http://msdn.microsoft.com/en-us/library/aa242706%28v=vs.60%29.aspx

VB.net Save File Dialogue error - Could not find special directory 'Desktop'

I have a fairly straight forward peice of code that just tries to set the default saved directory for a standard .net save dialogue to a specific folder. If that folder doesn't exist, it sets it to the desktop.
This works fine for everyone but one user who is getting the following error:
Could not find special directory 'Desktop'
How is that even possible?
'Check if folder exists
If Not IO.Directory.Exists(strDirectory) Then
strDirectory = FileIO.SpecialDirectories.Desktop
If Not IO.Directory.Exists(strDirectory) Then
strDirectory = IO.Directory.GetCurrentDirectory
End If
End If
'Show save file dialogue.
Dim folderDlg As New Windows.Forms.FolderBrowserDialog
folderDlg.RootFolder = Environment.SpecialFolder.Desktop
folderDlg.SelectedPath = strDirectory
folderDlg.ShowNewFolderButton = True
How about:
strDirectory = _
Environment.GetFolderPath(Environment.SpecialFolder.Desktop).ToString()
I use GetFolderPath() to get "My Documents" and it works fine (I don't ever have to think about it).