excel formula stopped working after saving and re-opening - excel-formula

I have a excel formula that does a formula based on data from another sheet. when i was setting it all up everything worked like a dream, the data updated when the home sheet was. I saved and closed. Now when i open it up and update the data the formula gives an #error
=COUNTIFS('G:\Call\[File_name_test.xlsx]CPC-Mas Nov 2013'!$M$28:$M$67,"R", 'G:\Call\[File_name_test.xlsx]CPC-Mas Nov 2013'!$C$28:$C$67, "JAC")
I've googled it but excel isnt my strongest!! Please help!

You can't refer to data in a closed workbook using that formula.
See alternative ways of referencing data in closed workbooks.
ie.
Sub ExecMacro4Excel()
Dim path As String
Dim workbookName As String
Dim worksheetName As String
Dim cell As String
Dim returnedValue As String
path = "C:\Users\" & Environ$("username") & "\Desktop\"
workbookName = "book2.xlsm"
worksheetName = "Sheet1"
cell = "A1"
returnedValue = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cell).Address(True, True, -4150)
MsgBox ExecuteExcel4Macro(returnedValue)
End Sub

Related

Referencing Previous Version of File using Filename

I am saving workbooks with v[ ] next to them to differentiate between latest and earlier versions.
Workbook v1
Workbook v2
...
Workbook v365
Is there a way to create a dynamic formula that does the following:
Detects the current version (365)
References a specific cell (e.g. A2) in the previous version (Workbook v364)
Please let me know! Any help would be really appreciated.
Since you did not answer my clarification questions, the next code will assume that the current workbook is the active one, all versions exist in the same folder and the "reference cell" will be a range in the previous version workbook where from a value must be extracted and it will be found in a sheet named as the active one in the current workbook:
Sub referenceThePrevVersion()
Dim wb As Workbook, curVers As Long, curName As String
Dim prevVersName As String, refVal As Variant, arrCur
Const refCell As String = "A2"
Set wb = ActiveWorkbook 'it my be ThisWorkbook if you need this one where the code exists
curName = wb.name 'the current workbook name
arrCur = Split(curName) 'split its name by spaces and place the words in an array
curVers = CLng(Mid(Split(arrCur(UBound(arrCur)), ".")(0), 2)) 'extract the current version
prevVersName = VBA.replace(curName, "v" & curVers, "v" & curVers - 1) 'obtain the prev version decreasing a unit
'extract the value of refCell, without opening the previous workbook:
refVal = CellV(wb.Path & "\", prevVersName, wb.ActiveSheet.name, Range(refCell).address(, , xlR1C1))
MsgBox refVal 'show the extracted value...
End Sub
Private Function CellV(fpath As String, fName As String, SheetName As String, strRange As String) As Variant
Dim strForm As String
strForm = "'" & fpath & "[" & fName & "]" & SheetName & "'!" & strRange
CellV = Application.ExecuteExcel4Macro(strForm)
End Function
The extracted value is CellV. It now is shown in a message, you may use it as you need.
Of course, if you know the previous version name and its path, you can open it and do whatever you need with its data.
Please, send some feedback after testing the code. If something not clear enough, do not hesitate to ask for clarifications.

How to make folder path universal?

New to VBA and have an assignment to create a sub that pastes from one workbook into a new workbook. A requirement for saving the file is that "the folder path be universal so other people can create this folder too". What amendment would I make to the ActiveWorkbook.SaveAs method to fulfill this? Thanks
Sub pasteTable()
Dim formatting As Variant 'create variable to hold formatting2 workbook path
formatting = Application.GetOpenFilename() 'user is prompted and selects path to formatting2 workbook and assigns to formatting variable
Workbooks.Open formatting 'formatting2 workbook is now active
Worksheets("Formatting").Range("B3:R13").Copy 'copies table from formatting2 workbook
Workbooks.Add 'add new workbook
Worksheets(1).Range("B3:R13").Select 'selects range on worksheet of new workbook to paste table
Selection.PasteSpecial xlPasteAll 'pastes table
Columns("B:R").ColumnWidth = 20 'ensures table has proper row and column heights/widths
Rows("3:13").RowHeight = 25
Worksheets(1).Name = "Table Data" 'renames worksheet
ActiveWorkbook.SaveAs "C:\Users\name\Desktop\names Excel Assessment VBA\names Excel Assessment VBA " & Format(Date, "dd/mmm/yyyy"), FileFormat:=xlOpenXMLWorkbookMacroEnabled
'saves workbook according to desired specifications
End Sub
Change your Save line to this:
ActiveWorkbook.SaveAs "C:\Users\" & Environ("Username") & "\Desktop\Excel Assessment VBA\Excel Assessment VBA " & Format(Date, "dd-mmm-yyyy") & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
The Username system variable will adjust depending on the Windows account that is in use. Just make sure each user has those folders existing on their desktop too, or you will get an error. I also removed names from the folder names as i assume you were trying to do something with the username there as well. You can adjust that to your needs.
Your Date format needed to change too as it was including illegal characters.
You also forgot to include a file extension, so I added that as well.
There is a lot going on with that line, including a lot of mistakes, so you are going to have to play with it a bit until you get exactly what you need. You may want to simplify it a bit until you get the hang of all those things.
I think you have to add some more checks
The script expects the name of the tool-path-folder as constant ToolFolder.
Plus a second constant ToolBaseFolder that could be set to the parent-path `ToolFolder, e.g. a network path. If the const is empty, users desktop will be used.
If this path does not yet exist it will be created.
Option Explicit
Private Const ToolBaseFolder As String = "" 'if ToolBaseFolder is an empty string desktop will be used instead
Private Const ToolFolder As String = "MyNameForToolFolder"
Public Sub testWbToToolFolder()
'this is just for testing
Dim wb As Workbook: Set wb = ActiveWorkbook
saveWbToToolFolder wb, "test.xlsx"
End Sub
Public Sub saveWbToToolFolder(wb As Workbook, filename As String)
'you don't need this sub - but have the same code line in your main routine
wb.SaveAs getToolFolder & filename
End Sub
Public Function getToolFolder() As String
'this returns the toolfolder e.g. C:\Users\xyz\Desktop\MyNameForToolFolder
Dim basepath As String
basepath = ToolBaseFolder & "\"
If existsFolder(basepath) = False Then
If LenB(ToolBaseFolder) > 0 Then
MsgBox ToolBaseFolder & " does not exist." & vbCrLf & _
"File will be saved to " & ToolFolder & " on desktop ", vbExclamation
End If
basepath = getDesktopFolderOfUser
End If
Dim fullpath As String
fullpath = basepath & ToolFolder & "\"
If existsFolder(fullpath) = False Then
makeFolder fullpath
End If
getToolFolder = fullpath
End Function
Private Function existsFolder(path As String) As Boolean
If Len(path) < 2 Then Exit Function 'can't be a valid folder
existsFolder = LenB(Dir(path, vbDirectory)) > 0
End Function
Private Function getDesktopFolderOfUser() As String
getDesktopFolderOfUser = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
End Function
Private Function makeFolder(path As String)
'https://stackoverflow.com/a/26934834/16578424 plus comment from rayzinnz
CreateObject("WScript.Shell").Run "cmd /c mkdir """ & path & """", 0, True
End Function

Rename excel file with VBA

I'm creating an excel file from nothing, adding content and saving it. I want to rename the excel file once I saved it, using VBA code. The file I want to rename isn't the same file in which I'm writing the code.
Currently I'm trying to do it this way (this is a snippet of my code, just to show how I'm saving the file):
Dim workbook1 As Workbook
Dim name As String, lastcell As String
Dim oldname As String, newname As String
Set workbook1 = Application.Workbooks.Add
name = "financial report - "
workbook1.SaveAs ThisWorkbook.Path & "\" & name & ".xlsx"
'lastcell has a date that I want in my new title
lastcell = Range("A1").End(xlDown).Text
oldname = ThisWorkbook.Path & "\" & name & ".xlsx"
newname = ThisWorkbook.Path & "\" & name & lastcell & ".xlsx"
Name oldname As newname
But when I run it I get this:
The value in my lastcell variable is supposed to be in a date format like this dd/mm/yyyy. The exact cell I'm trying to copy and use as part of the name of my new excel is 05/02/2021.
The value in name by the end of the sub should be financial report - 05/02/2021.
I'm gonna be surprised if this hasn't been asked before. Does anybody know what I'm doing wrong or have any recomendations for my code?
You need to provide a date value which can work as part of a filename:
lastcell = Format(Range("A1").End(xlDown),"yyyy-mm-dd")
Check out
https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.savecopyas
workbook1.SaveCopyAs newname
There you have your issue 05/02/2021 cannot be part of the file name as a slash / is not allowed in file names. Slash and backslash are considered to be path seperators.
Try the following: Make sure the variables are declared properly as below, to ensure the date is read as numerical date and not as some text that cannot be formatted.
Dim Name As String
Name = "financial report - "
Dim ReportDate As Date
ReportDate = Range("A1").End(xlDown).Value 'make sure you read the `.Value` not `.Text`
workbook1.SaveAs ThisWorkbook.Path & "\" & Name & ".xlsx"
workbook1.SaveCopyAs ThisWorkbook.Path & "\" & Name & Format$(ReportDate, "yyyy-mm-dd") ".xlsx"
Also use .SaveAs to save the original workbook and .SaveCopyAs to save the copy with the date attached.

Why am I getting an object required error when trying to get user input for the name of a workbook

I'm trying to insert formulas into my worksheet, but my first and second attempts haven't gone so well.
So, first I thought it would be better to use the GetOpenFilename feature for accuracy's sake, rather than having the user input the name of the workbook themselves. I used this page and this answer while writing it. When I run the code, the Open dialogue box opens, but when I select a workbook I keep getting a:
"Runtime Error '424': object required".
I'm not sure what it's asking for? At first I had just Application.GetOpenFilename(), so I thought I needed to add the filter, but it didn't help.
Sub openfile()
Dim mainwb As Workbook
Set mainwb = Application.GetOpenFilename("Microsoft Excel Files, *.xls*")
Dim mainws As Worksheet
mainws = InputBox("Please enter the name of the worksheet")
Dim rdsMonthly As Variant
rdsMonthly = InputBox("Please insert current month column in format $A:$A")
Dim rdsID As Variant
rdsID = InputBox("Please insert ID column in format $A:$A")
Cells(8, 14) = "=IFERROR(SUMIFS('[" & mainwb & "]" & mainws & "'!" & rdsMonthly & ", '[" & mainwb & "]" & mainws & "'!" & rdsID & ", $C55), " & Chr(34) & Chr(34) & ")"
End Sub
After, I tried using an Input box instead
Dim mainwb As Workbook
mainwb = InputBox("Please enter the name of the workbook, including file extension")
But that's giving me a:
"Runtime error '91': Object variable or With block variable not set".
I have no idea what it wants from me, and I'd really appreciate any help!
To get the name of the workbook, indicated with .GetOpenFileName, you may split once the big string through / and then get the last item. Then, split again by .xls and take the 0th item. With 1 line this 2 operations look like this:
Sub TestMe()
Dim filePath As String
filePath = Application.GetOpenFilename("Microsoft Excel Files, *.xls*")
Dim nameOfWb As String
'do not do this at production, but split it to variables:
nameOfWb = Split(Split(filePath, "\")(UBound(Split(filePath, "\"))), ".xls")(0)
Debug.Print nameOfWb
End Sub
Application.GetOpenFilename("Microsoft Excel Files, *.xls*") returns a string of the workbook path. And Workbooks() needs a workbook name, which is already opened.
Try this:
Sub TestMe()
Dim mainwb As Workbook
Set mainwb = Workbooks.Open(Application.GetOpenFilename("Microsoft Excel Files, *.xls*"))
MsgBox mainwb.Name
End Sub
Application.GetOpenFileName

error on getting the name of first sheet into the formula using macro excel 2007

I have tried with the code below in Excel 2007 and it generates a run time error 1004. I have tried with different ways to solve but could not. Need help in solving error because each of my first worksheet is named different.
Dim shtName As String
shtName = ActiveWorkbook.Worksheets(1).Name
Worksheets(2).Range("F2").Formula = "=AVERAGEIFS(&shtName!E:E,&shtName!A:A,"">="" & A2,&shtName!A:A,""<"" & B2)"
You need to insert the value of your shtName variable into the formula, not the variable name itself:
Dim shtName As String
shtName = ActiveWorkbook.Worksheets(1).Name
Worksheets(2).Range("F2").Formula = "=AVERAGEIFS('" & shtName & "'!E:E,'" & shtName & "'!A:A,"">="" & A2,'" & shtName & "'!A:A,""<"" & B2)"
(And it is usually a good idea to wrap sheet names in single-quotation marks to avoid problems if the name includes a space, etc.)
You should detach your variables from strings by putting them outside the "" marks.
So it is supposed to be
Dim shtName As String
shtName = ActiveWorkbook.Worksheets(1).Name
Worksheets(2).Range("F2").Formula = "=AVERAGEIFS(" & shtName & "!E:E," & shtName & "!A:A,"">="" & A2," & shtName & "!A:A,""<"" & B2)"

Resources