closing an active excel file knowing fraction of the name - vba

I have opened a file given the fraction of the name, where i equals to 142 as per below code.
Workbooks.Open Filename:=FilePath3 & "" & i & "."
After switching back and forth between other files is it possible to return back to this file and close it? I cant figure out how to Reference/Activate it, given I only have fraction of the name.
Thanks

I guess, after you open this file it's automatically activated, so I'd make it like:
Dim fileName as String
Workbooks.Open Filename:=FilePath3 & "" & i & "."
fileName = ActiveWorkbook.Name
and from this moment you can close your file at any time with something like:
Workbooks(fileName ).Close (False)
use (False) only if you don't want to save it

Related

Open the same workbook but different path every week

I would like to open a file that is located in a different folder every week (file name remains the same but new week = new data).
Workbooks.Open "C:\Users\baguette\Documents\W44\L060.xlsx"
The week folder is obviously W44. Is there a way I could use a cell content that would be taken into account in the code?
For example, cell A1 of sheet1 of the file the code is run from would contain the week number that I would manually key in before running the procedure.
I tried this but did not work :
Workbooks.Open "C:\Users\baguette\Documents\& ThisWorkbook.Worksheets(1).Range("A1")\L060.xlsx"
I guess it was a bit rash.
Thank you for your help.
You are very close to your solution. Just try below-
Workbooks.Open "C:\Users\baguette\Documents\" & _
ThisWorkbook.Worksheets(1).Range("A1") & _
"\L060.xlsx"
You can decorate code using string type variable. Check below sub.
Sub OpenSpecificFile()
Dim FolderPath As String
Dim WeekFolder As String
FolderPath = "C:\Users\baguette\Documents\"
WeekFolder = ThisWorkbook.Worksheets(1).Range("A1")
Workbooks.Open (FolderPath & WeekFolder & "\L060.xlsx")
End Sub

VBA unable to move on to next file in Directory, instead picking file named ".."

I am having a little issue with the Loop function to open files within a Directory. Find the code below:
'Build the complete folder path:
strTargetFolder_Batch = "I:\PerfTeam"
strTargetFolder_Batch = strTargetFolder_Batch & strMonthNo & " " & strMonthName & " " & strYear & "\" & "Attribution - Draft"
If Right(strTargetFolder_Batch, 1) <> "\" Then
strTargetFolder_Batch = strTargetFolder_Batch & "\"
End If
If Not CreateFolder(strTargetFolder_Batch) Then
MsgBox "Unable to create the folder:" & vbCrLf & strTargetFolder_Batch, vbExclamation
Else
End If
FolderPath = strTargetFolder_Batch
'Sets Parameters to Open the file
MyFolder = FolderPath 'location of files
MyExtension = "*.xlsx*"
MyFile = Dir(MyFolder & MyExtension)
Do While MyFile <> "" 'will start LOOP until all files in MyFolder have been looped through
Set oWbk = Workbooks.Open(MyFolder & "\" & MyFile)
*Batch Run is a Boolean function*
'*** 1. Calls Import Data Macro, which Imports the Data ***'
Call Import_new_data(Batch_Run, oWbk)
'*** 2. Calls Data Collector Macro, which Analyses the Data ***'
Call Data_Collector(Batch_Run)
'*** 3. Calls Report Production Macro, which Produces Report ***'
Call Report_Production_Sub(Batch_Run)
ContinueLoop:
MyFile = Dir
'**^^ Here is where the Macro breaks after completing a full first iteration** !
Loop
What essentially the macro does, it picks up data from the opened file, closes the file and then analyses it, before creating a report out of it. It should then move on the second file in the folder and perform the same operation.
While the first file gets opened fine, and analysed as it should, the problem arises moving on to the second file. The variable MyFile in fact picks up a 'Ghost' file named ".." which then throws an error of course as it does not exist. Doing some research I have found out this may relate to the Directory path.
Any help would be super appreciated!
Calling the Dir function with parameter starts a search for matching files. If nothing is specified as second parameter, is will search only regular files (no directories, no hidden files etc).
Any following calls to Dir (without parameter) will continue the last search initiated by a Dir(with parameter).
The .. you get as result of the Dir within your loop is not a file, it's a folder (up directory). You will get this only when you started a Dir with option vbDirectory as second parameter. As this parameter is missing in your code, I would strongly assume that anywhere in your code (that is not displayed) a new Dir-search is started (which destroys the search results of a previous Dir-search).
Update: If you need to check if a folder exists but don't want to destroy your Dir-Loop, you could use the FileSystemObject. The FileSystemObject is usefull for several things concerning files and folders.
if CreateObject("Scripting.FileSystemObject").FolderExists("<enter your path>") then

file not found VBA

I am having a frustrating time trying to do create a backup script in VBA. I get an error 'File not found' when trying to kill a file after opening it, making a backup and saving it under a new name.
Application.Workbooks.Open Old
ActiveWorkbook.SaveAs Archive
ActiveWorkbook.SaveAs New
'If Len(Dir$(Old)) > 0 Then Kill Old
If Len(Dir$(Old)) = 0 Then MsgBox ("bleuh")
'Here is where I get the message "Bleuh" even though Old was just opened a few lines ago..
The first line works fine, but when I want to kill the file 'Old', I get the error. Hence, I tried to test whether the file existed. The result was the Msg "Bleuh". So the file can be opened, but not found a few lines later. Can anyone explain this and help me?
In order to be complete, the entire code is found down here.
Sub UpdateAll()
Dim Afk As String, J As String, NJ As String, Path As String, strFile As String, Old As String, Archive As String, New As String
'Dim fso As Object
Path = "C:\Users\Name\OneDrive - Company\Desktop\Testing backup" & "\"
Year = Year(Date)
VJ = Year
NJ = Year + 1
Application.ScreenUpdating = False
'test for Afk (I define Afk for some additional functions that are not relevant for this problem)
Afk = "ABA"
'filenames
Old = Path & ("Planning ") & VJ & Space(1) & Afk
Archive = Path & ("Planning\Archive ") & VJ & Space(1) & Afk
New = Path & ("Planning ") & NJ & Space(1) & Afk
Application.Workbooks.Open Old
ActiveWorkbook.SaveAs Archive
ActiveWorkbook.SaveAs New
If Len(Dir$(Oud)) > 0 Then Kill Old
If Len(Dir$(Oud)) = 0 Then MsgBox ("bleuh")
'Here is where I get the message "Bleuh" even though Old was just opened a few lines ago..
'Also tried
'fso.CopyFile Old, Archive 'AND
'FileCopy Old, Archive
'in combination with:
'Name Old As New
' "SSDD"
'Next
Application.ScreenUpdating = True
End Sub
After analyzing your code I realized you don't need to open your file ('cause you don't get any information from it). You just want to move it. So, try the following:
Name Old as Archive
This should do the trick...

VBA saving Excel to Sharepoint freezes forever with a screen showing “Getting list of available content types and properties…”

I have VBA that, along with a whole lot of other stuff, saves an excel workbook to SharePoint (enterprise 2010 I think) and it works fine most of the time but every once in while, when a user runs the VBA, the Excel freezes with a pop up showing "Getting list of available content types and properties...". If the user selects cancel another pop up come up "Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed. If the user selects 'Debug' the last line of VBA is highlighted as creating the error.
Dim fileName As String
Dim excelDirName As String
fileName = [c9]
excelDirName = [c16] & "/"
ThisWorkbook.SaveAs excelDirName & fileName & ".xls"
Since this works sometimes (and it worked for over 6 months without this happening) and not other times I am not sure what it could be and I am thinking something was updated in SharePoint.
I would write it a bit differently, so as to make it more robust:
With SomeSpecificSheet
Dim path As String
path = .Range("SavePath").Value
Dim fileName As String
fileName = .Range("SaveFileName").Value
End With
Debug.Assert Trim(path) <> vbNullString
Debug.Assert Trim(fileName) <> vbNullString
Dim savePath As String
savePath = path & "/" & fileName
ThisWorkbook.SaveAs savePath
Note:
Be explicit about the worksheet you're reading from - you're currently reading from whatever the active sheet is, and unless every single worksheet in ThisWorkbook has the expected values in $C$9 and $C$16, that's asking for trouble.
Use named ranges, so that if a user inserts a column before column C or a row before row 9, your code still refers to the correct cells.
Let SaveAs determine the file's extension.
Use Debug.Assert to verify assumptions (and break before you freeze). Alternatively, you can explicitly validate the values, for example:
If path = vbNullString Or fileName = vbNullString Then
MsgBox "I need a path!"
Exit Sub
End If

Using VBA, how do I save a file in a relative directory

I have the following code to save the contents of an Excel Workbook as a tab delimited file.
Sub maketxtfile(className As String, rosterFileHandle As String)
Dim i As Long, gradebookContent As String
With Worksheets(className).UsedRange
For i = 1 To .Rows.Count
gradebookContent = gradebookContent & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(i).Value)), vbTab)
Next
End With
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
End Sub
The problem is that I don't want the tab delimited file to reside in the same directory as the xlsm file. I would like the file to reside in a subdirectory. I've seen solutions posted using absolute path names. That's not an option for me, I don't necessarily know what the path name will be in advance.
I thought I could do something like:
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", "rosters/" & rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
But this got me an error. Though I'm working on a Mac, I tried using "rosters\" but while this worked, it did not place my file in the subdirectory, but in a file with \\ in its path name.
I would greatly appreciate a solution that will show me how to do this using relative path names.
Incidentally, I would not mind first creating the tab delimited file in the current directory and then moving it into a subdirectory.
Mac uses : as the path separator; it only looks weird if you're used to DOS/Windows. Or perhaps if you're a dyslexic *nix user ;-).
If by "my other machines" you mean Windows boxes, then no, it won't be portable, since the colon is restricted to delimiting drive letters in file names. Best bet is to do something like this:
Function PathSep() As String
#If Mac Then
PathSep = ":"
#Else
PathSep = "\"
#End If
End Function
Then you could:
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", "." & PathSep & "rosters" & PathSep & rosterFileHandle) For Output As #1
After much searching, I found something that works.
I can write:
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", ".:rosters:" & rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
The syntax seems a bit weird using ":" to indicate the directory path, but it works. Now the question is whether this is portable and will work correctly on my other machines.
This should do the trick
ThisWorkbook.SaveAs (ThisWorkbook.Path & "\Rosters\" & ThisWorkbook.Name)
Edit:
Changed code to save the text file in stead also used chr(92) to reporesent the path seperator.
Sub maketxtfile()
Dim i As Long, gradebookContent As String
Dim rosterFileHandle As String
rosterFileHandle = "tabtest.txt"
rosterFileHandle = ThisWorkbook.Path & Chr(92) & "Rosters" & Chr(92) & rosterFileHandle
With ActiveSheet.UsedRange
For i = 1 To 10
gradebookContent = gradebookContent & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(i).Value)), vbTab)
Next
End With
Open (rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
End Sub