Excel VBA File not Found although file exists - excel

I have written below piece of code to access a file and copy content from one file to the other. I am using excel 2007.
Sub copypaste()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\Users\user\Desktop\sample\"
strFileName = Dir(strFolder & "*.xlsx")
Dim eRow
Dim a As Variant
Dim b As Variant
Do While Len(strFileName) > 0
**Set wb = Workbooks.Open(strFileName)**
a = Cells(7, 7)
b = Range("D11:F11")
ActiveWorkbook.Close
Worksheets("sheet1").Cells(7, 7) = a
Worksheets("sheet1").Cells(7, 8) = b
strFileName = Dir
Loop
End Sub
Although the file exists in the folder I get the error while opening the file. While in debug mode the variable strFileName contains the file name but still the file is not opening. I am getting the error at line "Set wb = Workbooks.Open(strFileName)"
Thanks in advance for your help!!

Workbooks.Open requires the full path to the workbook. I suspect you want:
Set wb = Workbooks.Open(strFolder & strFileName)

You need to replace all \ by double \\ in your path
Or add # in front of you string.
It is cause \ is the character for escape strings, like \n \s and so on so letter after a \ is transformed.
Try to print your path, you'll see what append.
EDIT
May also try :
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),");
Set wb2 = Workbooks.Open(Filename:=FileToOpen)

As (gone) user user496736 stated you need to have a full path
But most of the time your path will be very long and cumbersome to type or you will not know it in advance, so the help of ActiveWorkbook.Path
Exemple with readonly just for information
Dim Alloc_WB As Workbook
Dim FileStr As String
FileStr = ActiveWorkbook.Path & "\" & "my_file.xlsx"
'workbook should be closed at start of code. Otherwise you get an error msg asking to re-open the Workbook
Set Alloc_WB = Workbooks.Open(Filename:=FileStr, ReadOnly:=True)
'...
'Other actions here...
'...
With Alloc_WB
.Close
End With

Related

Remove known password from directory of Excel files with VBA

I have found this VBA code and it works to remove the known password on one Excel workbook just fine.
Sub testPasswordRemoval()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="C:\Temp\Book2.xlsm", Password:="pw")
wb.Password = ""
wb.SaveAs "C:\Temp\NewBook.xlsm"
End Sub
But, I have tried various tutorials and videos (many folks offering this) but none of them work to loop through a folder of .xlsx files (all with the same known password) and remove that same password.
I am not a VBA person, but have spent about 16 hours over the past three days trying to crack the code on this one. I have found several examples of looping over files in a directory, but none that enabled me to put the above code into them and loop and remove passwords.
Try this code, read the comments, and adjust it to fit your needs
Code:
Public Sub RemovePassLoopThroughFiles()
Dim targetWorkbook As Workbook
Dim filePath As String
Dim folderPath As String
Dim folderWildcard As String
Dim currentFileName As String
Dim currentFileExtension As String
Dim newFileName As String
Dim newfileNameSuffix As String
Dim currentPassword As String
Dim newPassword As String
' Adjust next lines to fit your needs
folderPath = "C:\Temp\" ' With slash at the end
folderWildcard = "*.xls*" ' You can change the suffix to open specific files
newfileNameSuffix = "_NoPassword"
currentPassword = "pw"
newPassword = ""
' Get the file path concat folder and wildcards
filePath = Dir(folderPath & folderWildcard)
Do While Len(filePath) > 0
' Open the workbook and set reference
Set targetWorkbook = Workbooks.Open(Filename:=filePath, Password:=currentPassword)
' Get current file extension
currentFileExtension = Right(filePath, Len(filePath) - InStrRev(filePath, "."))
' Get filename no extension
currentFileName = Left(filePath, InStrRev(filePath, ".") - 1)
' Build new fileName
newFileName = currentFileName & newfileNameSuffix & "." & currentFileExtension
' Set new password
targetWorkbook.Password = newPassword
' Save new file
targetWorkbook.SaveAs folderPath & newFileName
'Debug.Print filePath
filePath = Dir
targetWorkbook.Close True
Set targetWorkbook = Nothing
Loop
End Sub
Let me know if it works.

Looping code error-Excel says that it can't find the file

I'm trying to write a code that will refresh all workbooks starting with 'FY' in a folder. With the current code, the first two workbooks refresh, but when it comes to the third workbook, I get this error:
Sorry, we couldn't find FY20 11-15.xlsm\FY20 1-5.xlsm. Is it possible it was moved, renamed or deleted?"
The path to the workbook is "C:\Documents\Database\Sales".
Here's the code:
Sub refreshdata()
Dim file As String
Dim book As String
file = Application.ThisWorkbook.Path
book = Dir(file & "\FY*.xlsm")
Do While file <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(file & "\" & book)
Call Refresh
wb.Close savechanges:=True
file = Dir
Loop
End Sub
You named your variables not clearly and file contains actually a path file = Application.ThisWorkbook.Path therefore you mixed everything up. Get your variable names more meaningful! Make sure your variables are well named after what content they contain or you confuse yourself.
Sub refreshdata()
Dim Path As String
Path = Application.ThisWorkbook.Path
Dim FileName As String
FileName = Dir(Path & "\FY*.xlsm")
Do While FileName <> vbNullString
Dim wb As Workbook
Set wb = Workbooks.Open(Path & "\" & FileName)
Call Refresh
wb.Close SaveChanges:=True
FileName = Dir
Loop
End Sub
What was wrong?
Here file = Dir you set your file variable which actually was the path to filename. And in the next iteration of the loop Set wb = Workbooks.Open(file & "\" & book) is twice a filename, the new filename in file and the old in book.

Problems with Worksheetfunction.Match in a closed workbook. Cannot work out why no match is found

I'm writing a code to delete a log entry in a .csv file. The code starts with opening the .csv file, using Application.Match to return the row number, and then deleting that and closing the file again. The problems I'm experiencing are I get a type mismatch (my error handling is activated) OR (and here it gets weird) it works (a match is found, the row is deleted) but then the logfile is messed up - all data is one string in column a with either ";" or "," delimiters (this varies somehow, relevant note: I use Dutch language excel). Of course, this makes it impossible for the macro to find a match in any case.
I found that the type mismatch problems I'm experiencing will most likely be caused by the code not finding a match, and this is what I don't understand since I checked and doublechecked the input and the data in the logfile - by all means it simply should find a match. And sometimes it does find a match, deletes the row and messes up formatting. (NOTE: Mostly it does NOT find a match.)
I check data in the .csv file before running the macro. I have tried running the macro with the .csv file already opened. I have tried to Set the matchArray from outside the With. I have tried both sweet talking my laptop and a more aggressive approach, to no avail.
Sub DeleteRowFromFile(ByVal matchValue As String)
Dim filePath As String
Dim fileName As String
Dim fileType As String
Dim matchArray As Range
Dim rowToDelete As Variant
'Naming variables for flexibility
filePath = "C:\Users\Maxim\Documents\Log\"
fileName = "TestRegister"
fileType = ".csv"
Application.ScreenUpdating = False
Workbooks.Open (filePath & fileName & fileType)
With Workbooks(fileName).Worksheets(1)
Set matchArray = .Range("A:A") 'set range in the logfile
'Type mismatch here:
rowToDelete = Application.Match(matchValue, matchArray, 0)
If Not IsError(rowToDelete) Then
Rows(rowToDelete).Delete
Else:
MsgBox "Orderno. " & matchValue & " not found.", vbOKOnly + vbExclamation, "Error"
End If
End With
'Closing the log file
Workbooks(fileName).Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
Sub MatchAndDelete()
Dim matchValueRange As String
matchValueRange = ActiveWorkbook.Worksheets(1).Range("A1").Value
DeleteRowFromFile (matchValueRange)
End Sub
Footnote:
I'm a struggling enthusiast, I have a lot to learn. Sorry in advance if I have left out any crucial information for you to be of help, and thanks a lot for any and all help.
When you open or save a csv file using a VBA macro Excel will always use the standard (US English delimiters) while if you do the same via the user interface it will use the separators as defined in the Windows regional settings, which probably is ";" in your case.
You can check with .?application.International(xlListSeparator) in the immediate window of your VBEditor.
You can tell Excel to use a different separator, by e.g. adding sep=; as line 1 of your file. Hoever this entry is gone after opening the file. The following code - added before you open the csv file will add this:
Dim oFSo As Object
Dim oTxtFile As Object
Dim strData As String
Set oFSo = CreateObject("Scripting.FileSystemObject")
strData = oFSo.OpenTextFile(filePath & fileName & fileType, 1).ReadAll
Set oTxtFile = oFSo.OpenTextFile(filePath & fileName & fileType, 2)
oTxtFile.writeline "sep=;"
oTxtFile.writeline strData
oTxtFile.Close
You can save your changed file by using the Excel UserInterface Shortcuts via the Application.SendKeys thus achieving what you want:
Application.SendKeys ("^s") 'Save
Application.SendKeys ("^{F4}") 'Close
Dont run this code from the VBE Immeditate window as it will probabaly act on the wrong file!
The full code - just with an alternate way to make the requested change:
Sub DeleteRowFromFile(ByVal matchValue As String)
Dim filePath As String
Dim fileName As String
Dim fileType As String
Dim matchArray As Range
Dim rowToDelete As Variant
Dim oFSo As Object
Dim oTxtFile As Object
Dim strData As String
Dim content As Variant
Dim i As Long
'Naming variables for flexibility
filePath = "C:\Users\Maxim\Documents\Log\"
fileName = "TestRegister"
fileType = ".csv"
Application.ScreenUpdating = False
'Adding "sep =" ; as line 1 of the log file
Set oFSo = CreateObject("Scripting.FileSystemObject")
strData = oFSo.OpenTextFile(filePath & fileName & fileType, 1).ReadAll
Set oTxtFile = oFSo.OpenTextFile(filePath & fileName & fileType, 2)
oTxtFile.writeline "sep=;"
oTxtFile.writeline strData
oTxtFile.Close
'Open logfile
Workbooks.Open (filePath & fileName & fileType)
'Make your changes
With Workbooks(fileName).Worksheets(1)
content = .UsedRange.Value
For i = UBound(content, 1) To 1 Step -1
If content(i, 1) = matchValue Then
.Rows(i).Delete
End If
Next i
End With
'Closing the log file via Sendkeys using excel shortcuts
Application.SendKeys ("^s") 'Save
Application.SendKeys ("^{F4}") 'Close
Application.ScreenUpdating = True
I think that Match it is not required. Try this one.
Sub DeleteRowFromFile(ByVal matchValue As String)
Dim filePath As String
Dim fileName As String
Dim fileType As String
Dim matchArray As Range
Dim rowToDelete As Variant
'Naming variables for flexibility
filePath = "C:\Users\Maxim\Documents\Log\"
fileName = "TestRegister"
fileType = ".csv"
Application.ScreenUpdating = False
Workbooks.Open (filePath & fileName & fileType)
With Workbooks(fileName).Worksheets(1)
For i = .UsedRange.SpecialCells(xlCellTypeLastCell).Row To 1 Step -1
If .Cells(i, 1).Value2 = matchValue Then
.Cells(i, 1).EntireRow.Delete
End If
Next
End With
'Closing the log file
Workbooks(fileName & fileType).SaveAs Filename:= _
(filePath & fileName & fileType) _
, FileFormat:=xlCSVMSDOS, CreateBackup:=False 'Saving the file
Workbooks(fileName & fileType).Close 'Closing the file
Application.ScreenUpdating = True
End Sub
Hope it helps

How to open files contained in a folder in current file path

I want to open a file (file) that is stored in a folder (Source) which is in the same directory as the current workbook. I get a runtime error 1004 indicating that it the file can't be located. What am I doing worng?
Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file*.xlsx")
Since you want the wildcard to stay, you need to loop through the files in the folder. Something like this may be of interest to you:
Sub FileOpen()
Dim sPath As String
Dim sFile As String
Dim wb As Workbook
sPath = ThisWorkbook.Path & "\Source\"
sFile = Dir(sPath & "file*.xlsx")
' Loops while there is a next file found in the specified directory
' When there is no next file the Dir() returns an empty string ""
Do While sFile <> ""
' Prints the full path of the found file
Debug.Print sPath & sFile
' Opens the currently found file
Set wb = Workbooks.Open(sPath & sFile)
' Place your code here
' Place your code here
' Place your code here
' Close the current workbook and move on to the next
wb.Close
' This line calls the Dir() function again to get the next file
sFile = Dir()
Loop
End Sub
Good luck!
Replace the wildcard with actual filename.
Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file.xlsx"
I changed the file*.xlsx to file. xlsx...hope your code works.
thanks.

VBA: If filename.dat in folder contains X, open, run macro, save as filename.xlsm, close

I am trying to create a macro that will search a folder for a .dat file that contains "OPS"(not case sensitive) in the name, if it finds a file I would like to open it and run another macro, save the file as the original filename.xlsm, and close.
So far, I am able to search for the name but that's about the extent of my knowledge.
Sub Test2()
Dim sh As Worksheet, lr As Long, fPath As String, fName As String, rFile() As Variant
fPath = "C:\Users\ntunstall\Desktop\test\"
ctr = 1
fName = dir(fPath & "*.dat")
Do Until fName = ""
If InStr(fName, "OPS") > 0 Then
ReDim Preserve rFile(1 To ctr)
rFile(ctr) = fName
ctr = ctr + 1
End If
fName = dir
Loop
For i = LBound(rFile) To UBound(rFile)
'The variable rFile(i) represents the workbooks you want to work with.
MsgBox rFile(i)
Next
End Sub
Ideally, this macro would run any time a .dat file containing OPS in the filename is opened. Any help is appreciated, thanks.
To the top add
Dim wb as workbook
and then replace your message box line with
Set wb = Workbooks.Open(fPath & rFile(i))
wb.SaveAs fPath & Split(rFile(i), ".")(0), xlOpenXMLWorkbookMacroEnabled
wb.Close
I tested with a tab deliminated file and it worked well. Your issues may vary if you have a different format.

Resources