Macro Run only if it is a false file name added - excel

I have a Macro that Loops through Folder where xlsm file is and finds the File based on a condition to match the given part of the file with the file in Folder and skip it. The file full name is 03_2020_STR_BB_2080.xls. Code works perfectly, but my problem starts when I introduce the correct number in this case. 2080 as shown below. When I click on Run button to run the code the Macro doesn't start at all, but when I insert a False value then instead of 2080 any other number or text that is not a part of a file when I click on Run then Macro starts to Run.
Can anybody help me, tnx in advance.
In my folder are three files
03_2020_STR_BB_2080.xls
03_2020_STR_BB_7080.xls
03_2020_STR_BB_2130.xls
I am using following part of a code.
Dim MyFile As String
Dim Filepath As String
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Fname As String
Filepath = ThisWorkbook.Path & "\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "BB2.xlsm" Then
Exit Sub
End If
If MyFile Like "*STR_BB_2080.xls" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
code continues....

Check by replacing the if condition with this line:
If MyFile Like "*STR_BB_2080*" Then

Related

Excel VBA won't save: creating 8-digit alphanumeric "filename"

I am new to VBA. I am using a "shell" macro to run another macro on a series of files. It won't save. I am going to include my code here and also a series of photos because the photos were the only way to show the result of hovering over the values in the code.
So, the error message is generating something I don't understand. But it is clear that the links in the code link to what the results should be, so I'm confused.
This is the code:
Sub SHELLforMacros()
Dim wbMatrix As Workbook
Dim strFileName As String
Dim strFileName As String
Dim newFileName As String
Dim strPath As String
Dim strExt As String
Dim objWorkbook As Workbook
Dim ws As Worksheet
Dim Sheetname As Worksheet
Set Sheetname = Worksheets(1)
Dim Worksheet As Worksheet
Dim rng As Range
Set rng = Range("A2")
strPath = "C:\Users\myname\Desktop\All_mricgcm3_files\45\Fall45\test\"
strExt = "csv"
strFileName = Dir(strPath & "*." & strExt)
While strFileName <> ""
Set wbMatrix = Workbooks.Open(strPath & strFileName)
Application.Run "'C:\Users\myname\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB'!Graph_NEW"
strPath = "C:\Users\myname\All_mricgcm3_files\45\Fall45\test\"
newFileName = Sheetname.Range("A2").Value
ActiveWorkbook.SaveAs fileName:=strPath & newFileName, FileFormat:=51
ActiveWorkbook.Close SaveChanges:=True
Wend
End Sub
What this macro is supposed to do is open a file, run another macro on the file (creating a graph), and then save the file with the same name but as an .xlsx file. Then open the next file in the folder and do the same, until it runs out of files. I realize the code may not be the most current. It is cobbled together from things I've found online. Thanks for any help.
Edit: UPDATE - I removed all the section on saving and closing the file from the "shell" macro and put it into the "Graph_NEW" macro. Now the "shell" macro is running fine. But I am running into the same issue with the "Graph_NEW" macro now. It is exactly the same error message as highlighted in the first image, only each time there is a new 8-digit alphanumeric "filename" that it is looking for. This seems like a very specific thing.
I changed the section in the following ways, successively, in an attempt to debug. I added With and End With around the section:
With WB
ActiveWorkbook.Save
newFileName = Sheetname.Range("A2").Value
strPath = "C:\Users\qmontana\All_mricgcm3_files\mric45\Fall45\test\"
ActiveWorkbook.SaveAs fileName:=strPath & newFileName & ".xlsx", FileFormat:=51
ActiveWorkbook.Close SaveChanges:=True
End With
I changed the name of the folder from "45" to "mric45" thinking that maybe it didn't like a number as a folder name.
I removed the "backslash" at the end of the strPath--and then the 8-digit alphanumeric string showed up as an error after the Fall45 folder, like this "C:\Users\myname\Desktop\All_mricgcm3_files\45\Fall45\777GTY78". Yet, as I've shown in the images, all indications are that it knows what file it is working with. There are no "blank spaces" in the pathname.
I tried taking the underscores out of the folder "All_mricgcm3_files".
I moved the line newFileName = Sheetname.Range("A2").Value to come before the strPath line.
Where is this 8-digit alphanumeric "filename" coming from?? (See error code, first image.)
Ok, it was a very simple thing, in case anyone else runs into this problem.
Took me two days to find out though --> I had somehow dropped a folder layer in the path name. The catch? The alphanumeric string was showing up at the end of the path name, not where the folder layer was missing. That's why I was thrown off because my focus was on the ending.
When I added that folder\ back in, I had no more problem with saving and the macro ran fine.

Problem with exporting data from the latest file

I have a problem with my macro in Excel VBA. This is my first macro... So, I have the first file, where is the button, which is opening the another file. In this another file I made an UserForm, where user cant check, on which area will do "something". And there is the start of my problems. I want, that when the user check the area, open the latest file in folder of this area xd so i foung the code and it works, next file opens, the I want split a part of this latest document where is the number of something and it also works, but I want to add this numba()+1 to this file, where the userform with possibility of checkig area is, alsa I want to after this splitting and export numba() to another file close this file, from I exported the numba(), but when I do Workbooks(My Path&Latest File).Close SaveChanges=False, Vba shows a mistake. So Can you help me with this problem? How to export this numba+1 from opening latest file to this accurate, where I work in fact?
Or maybe do you have any idea, how can I export only name of this latest file without opening it? Then i will export onlu name, split it and make the next number for this document ... Below I add codes, thanks for your help :)
Private Sub CommandButton1_Click()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xlsx", vbNormal)
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile
Dim numba() As String
numba() = Split(Range("I6"), "-")
Call NAZWA
Sub NAZWA()
This.Workbooks.Activate
Worksheets("Tabelle1").Activate
Range("I6") = "xx-xxxx-"
End Sub
Please, try Workbooks(LatestFile).close
Workbooks collection keeps only the workbooks name, not their full name...
Use this technique:
Dim MyOpenWb As Workbook
Set MyOpenWb = Workbooks.Open(MyPath & LatestFile) 'set a reference to the opened workbook for later use
'access any worsheet/cell in that workbook like
MyOpenWb.Worksheets("Sheet1").Range("A1").Value = "write into Sheet1 cell A1"
'make sure every Range/Cells/Columns/Rows has a workbook/worksheet specified
'otherwise it is not clear where Excel should look for Range("I6")
Dim numba() As String
numba() = Split(MyOpenWb.Worksheets("Tabelle1").Range("I6"), "-")
'do your stuff here …
'Close it
MyOpenWb.Close SaveChanges:=True 'or False
When ever you open a workbook set it to a variable eg MyOpenWb. You can then use this variable to access the workbook and also to close it. So you never have to deal with it's name or path again once it is open.
Avoid using .Select and .Activate instead access a range by naming its workbook and worksheet like below:
ThisWorkbook.Worksheets("Tabelle1").Range("I6").Value = "xx-xxxx-"
You might benefit from reading
How to avoid using Select in Excel VBA.

Saving a macro so that the file can be updated

Background Information - I have two buttons, that both run a set of code. The excel file has over 30 columns and 65,000 rows. This file is exported (.csv) from somewhere and is updated biweekly.
Goal - have the new file saved with the same name as the old. So that the values can be updated, buttons are still available and the code can run again with the new file.
Or That when a new file is exported, it is saved in a folder that runs the code INDEPENDENT of the user path. i.e Pathname = ActiveWorkbook.Path & "C:\Users\"this can be any name"\Desktop\Downloads\"
Attempt
Used a similar code to the one in a previous question "Run same excel macro on multiple excel files" with edits to tailor for my code. With no success
Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xls")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
Currently, when I attempt the first method I only replace (Old file + VBA) with (New file).
Please note that the solution does not need to be a VBA code. If it's just saving the file in a new method that stores the macro and updates the values I would be happy.
An example of my previous answer:
Sub SaveThisAs()
Dim wb As Workbook: Set wb = ThisWorkbook 'ThisWorkbook referrs to the workbook the macro is ran from
Dim PathToSaveTo As String
PathToSaveTo = wb.Path & "\"
PathToSaveTo = PathToSaveTo & Format(Now, "ddMMyyyy_hhmmss") & wb.Name 'Lets add a timestamp
'Do your macro stuff here
'....
'Save the workbook
wb.SaveAs PathToSaveTo
End Sub
Please note that I'm using wb.Name at the end of the file to save to... this will be fine first time you run this, but a second time the name will get longer... and longer ... and longer. Adjust as per your needs with an appropriate file name.

Mac Excel 2016 VBA - Workbook.open gives 1004 error

I'm trying to get a macro that works perfectly in Excel 2011 for Mac to work in Excel 2016 for mac. The goal is to have the user specify a folder with .csv files in it, and then the macro loops through all the .csvs, opening each to copy information out of it into another Workbook.
The macro fails when trying to open the first .csv file in the user-chosen folder, with a 1004 error, file cannot be found.
(side note: Earlier in the macro, workbooks.open works perfectly with a user selected FILE)
The macro is huge, so I made a brand new smaller one just to get past this problem. Here is the smaller, test code, which has the same failing behavior:
Sub Test()
Dim folderpath As Variant
Dim filename As Variant
Dim newfilename As Variant
Dim wb As Workbook
Dim newfolderpath As Variant
folderpath = MacScript("choose folder as string")
newfolderpath = Replace(folderpath, ":", "\")
MsgBox (newfolderpath)
filename = MacScript("Choose file as string")
newfilename = Replace(filename, ":", "\")
MsgBox (filename)
MsgBox (newfilename)
MsgBox (Dir(filename))
MsgBox (newfolderpath & Dir(filename))
Set wb = Workbooks.Open(newfolderpath & Dir(filename))
End Sub
All the msgboxes provide expected values.
newfolderpath= the whole path with \ separators.
filename= the whole path and file name with : separators.
newfilename= the whole path and file name with \ separators.
Dir(filename)= just the file name.
newfolderpath & Dir(filename))= the entire path and file name with \
separators.
Set wb line gives:
Run-time error '1004'
'Hard DRIVE\USERS\DAVE\DESKTOP\CSVS\1.CSV'
could not be found.
Clearly the file is there, openable and works.
Any help is greatly appreciated.
Well, I think I found the answer, or at least an answer that works for my project.
I went back to the workbooks.open(user-selected FILE) from earlier in the macro, and discovered it was reading it as "/users/Dave/Desktop/csvs/1.csv". So, even though debug and msgbox were returning backslashes, it was somehow wanting forward slashes (You were partially right, Tim). Additionally, it clearly truncates the name of the Mac hard drive, and starts with the users directory. So, I just modified the variables to match this format, and voila, it worked. For those who are interested, here's the modified code I wound up using:
Sub Test()
Dim folderpath As Variant
Dim newfilename As Variant
Dim wb As Workbook
Dim newfolderpath As Variant
Dim newfp As Variant
folderpath = MacScript("choose folder as string")
newfolderpath = Replace(folderpath, ":", "/")
newfp = Right(newfolderpath, Len(newfolderpath) - InStr(newfolderpath, "/") + 1)
newfilename = Dir(newfp)
Set wb = Workbooks.Open(newfp & newfilename)
Exit Sub
Thanks to everyone that helped.

how to read certain files in a directory in excel VBA

I want to read certain excel files from a directory and then open them in excel-2007 with VBA.
Here is an example:
directory: c:\temp
file pattern: is xxxxx0123.xls (xxxxx represents the file names).
I try to use Application.FileSearch, but it won't work in Excel 2007. Does any one have good suggestions?
Thanks in advance
You can use DIR to find files matching your pattern, ie this code opens these files, grabs their path, and closes the files again
The code can be made recursive if you need to look in sub-folders
Sub GetFiles()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\temp"
strFileName = Dir(strFolder & "\*123.xls")
Do While Len(strFileName) > 0
Set wb = Workbooks.Open(strFileName)
Debug.Print wb.FullName
wb.Close False
strFileName = Dir
Loop
End Sub

Resources