You mentioned something about making a change (at first) to make my code work. Can you elaborate if so? Was it the same issue OP is having?
@Gokhan Aycan,
No, it was something else but I can't remember exactly what. I do know that even on the first run my test file was not returned. Then I took a quick look at the structure of your code and left it for what it was. Until you made me doubt with your post #12, after which I again pasted your code into an empty workbook, modified the search folder and ran your code. Then the correct file was returned and also, with that file in a different folder, a second time after which I apologized to you.
Nevertheless, it still gnawed at me. Was I so wrong then the first time? Because I don't doubt myself so easily, I decided that I would go through your code line by line. Then the problem, which was initially difficult to reproduce, was quickly found. The cause lies in (reliance on) VBA's implicit vartype conversion.
The code line
VBA Code:
If InStr(oFile.Name, strProductCode) And InStr(oFile.Path, ".xls") Then
is based on three (obviously unconscious and unintentional) assumptions.
The first two and most obvious assumptions are that the variable
strProductCode
is supposed to contain only numerical characters (after all, they don't have uppercase and lowercase) and that the extension name of the file involved (XLSX / XLSM / XLST / XLSB) can never appear in uppercase. My test involved several files whose extension name was in uppercase. They were not considered by your code when it came to date and time stamp.
The third and final assumption was that VBA would convert every single statement in the above line to a Boolean vartype. In a single statement, VBA does that automatically, but in a double statement, as above, VBA sticks to the vartype returned by the invoked Instr function, which is a Long vartype.
I should have seen this right away, but didn't. Since you made me doubt I made a file called blahdieblah563412 v5.xlsx, dropped it in a folder somewhere and then modified your code as per below.
VBA Code:
If InStr(1, oFile.Name, strProductCode, vbTextCompare) And InStr(1, oFile.Path, ".xls", vbTextCompare) Then
Right in the first run meanwhile stepping through the code the file was ignored and then I got it. In the oFile.Name, the argument searched for (the code) started at position 12, while the ".xls" started at position 80. With a logical AND, the result of 12 And 80 is 0, and VBA converts that to False.
In my very first test I also used a random folder structure and a fresh (empty) file called 563412.xlsx but it was ignored several times. So in those scenarios, the ".xls" must have happened to have started in an even position. So I wasn't wrong the first time at all, although it did cost me some headaches ... LOL