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.
Related
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.
I found the code to open a file from a path (referring to a cell), as well as how to open a file when the complete file name is unknown, however, I'm unable to do both. Is this possible?
Open File From Path:
Dim google_ads_report As Workbook
Dim FromPath As String
' Get path from cell C14 on Report tab
FromPath = Workbooks("Monthly Report - Master.xlsm").Sheets("Macros").Range("C14")
' Make sure there is a backslash at the end of the from path
If Right(FromPath, 1) <> "\" Then FromPath = FromPath & "\"
'Set wkb = ThisWorkbook
Set google_ads_report = Workbooks.Open(FromPath & "hi.xlsx")
Open File with partial Name (because it changes every month):
GA_Transactions = VBA.FileSystem.Dir("C:\Users\tom\Desktop\Analytics Google Ads Revenue - Monthly*.xlsx")
Workbooks.Open "C:\Users\tom\Desktop\" & GA_Transactions
Weirdly, the partial file open code needs the directory both times which after coming across this problem and thinking about it, is strange, right?
I'm assuming there's a way to do it but I can't seem to do it/find it.
Thanks!
The only thing I can think of is looping through the specified folder, and checking if the file name has the required month text. See below code (not tested, but should point you in the right direction).
Option Explicit
Sub Open_File()
Dim fs As Object, sf As Object, file As Variant
Dim sFileName As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set sf = fs.GetFolder("C:\Users\tom\Desktop\")
sFileName = "Analytics Google Ads Revenue - Monthly"
For Each file In sf.Files
If InStr(file.Name, sFileName) > 0 Then
'file found - now execute open method
Exit For
End If
Next file
End Sub
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
Borrowed the code and tweaked. Everything worked fine until strPath2 only receives filename instead of the entire file path. After searching there is surprisingly no answer.
I basically want to let Dir find any file that contain the word "Hello" in its filename. The start and the end of the filename varies. Is there any function/method that returns the full directory path with filename as String?
Sub TransferData()
Dim strPath2 As String
Dim wbkWorkbook1 As Workbook
Dim wbkWorkbook2 As Workbook
strPath2 = Dir("C:\*Hello*.xlsx")
Set wbkWorkbook1 = ThisWorkbook
Set wbkWorkbook2 = Workbooks.Open(strPath2)
wbkWorkbook2.Worksheets("Sheet1").Range("A1:J20").Copy
wbkWorkbook1.Worksheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
End Sub
It's very simple. I figured it out myself.
strPath2 = "C:\" & Dir("C:\*Hello*.xlsx")
I am trying to find the command and correct coding to open a PDF file with a relative file path to the active excel file. The code below works fine as a link directly to the file. However, I just need this code snippet to find the PDF file that is sitting in the same file as the opened excel file and open accordingly.
Sub OpeningPDF()
'ThisWorkbook.FollowHyperlink "C:\Users\Michael\My Documents\totals\copy.pdf"
End Sub
I tried working with ThisWorkbook.path but nothing I tried with that worked or seemed to be outdate. Any help in this matter would be much appreciated.
I have found two solutions to this:
The first one is using the built-in Shell() function. This should automatically resolve the relative path (relative to the applications current working directory):
Public Sub StartExeWithArgument()
Dim strFilename As String
strFilename = "../folder/file.pdf"
Call Shell(strFilename, vbNormalFocus)
End Sub
The second one uses the Shell.Application COM Object and will basically do the same as the first one.
Sub runit()
Dim Shex As Object
Set Shex = CreateObject("Shell.Application")
tgtfile = "../folder/file.pdf"
Shex.Open (tgtfile)
End Sub
If you start with ThisWorkbook.Path and your relative-reference, then trim a layer off for every "..\" in the relative reference, you'll get the path.
Function RelativeToAbsolutePath(ByVal RelativePath As String) AS String
Dim TempStart AS String, TempEnd AS String
TempStart = ThisWorkbook.Path
TempEnd = RelativePath
If Left(TempEnd,1) = "\" Then TempEnd = Mid(TempEnd,1)
RelativeToAbsolutePath = ""
On Error GoTo FuncErr
While Left(TempEnd,3)="..\" AND InStrRev(TempStart,"\")>0
TempStart = Left(TempStart,InStrRev(TempStart,"\")-1) 'Remove 1 layer from Workbook path
TempEnd = Mid(TempEnd,4) 'Remove 1 instance of "..\"
Wend
RelativeToAbsolutePath = TempStart & "\" & TempEnd 'Stitch it all together
FuncErr: 'You may want a DIR(..) check to see if the file actually exists?
End Function
You can then open it with Shell