Ok so I am creating a Macro in Excel 2010. I am looking to project data in to the future. What I want to do is create a button in Excel "What if" that will allow me to freely edit the data. Then after I am done I would like to have another button "Reset" which if I pushed would reset the entire data set to what was previously there. Then if it were possible create another button. "Last Scenario" which would return the last "What if change."
For example use a excel with months Jan-Dec
Then with
Sales
Costs
Profits (Sales - Costs = Profits)
I would hopefully like to do this only having one excel sheet and doing all this without having to save outside of excel. If there was a way to save in a new sheet temporarly to recall from. Then it saves the Last Scenario until a new whatif is created which erases the old whatif.
Thanks
to save the current Excel file with a filename derived from cell A1
Public Sub SaveAsA1()
ThisFile = Range("A1").Value
ActiveWorkbook.SaveAs Filename:=ThisFile
End Sub
Related
So I am currently studying SQL Server but right now I am just working a standard office admin job while I'm studying.
I never really made macro's before and little knowledge on VB but decided to design a macro for work to make things a bit easier for my team.
The macro just very simply allows the user to enter data, stats etc and gives the percentage or average statistic resulting in a total letting the user know if the statistics have been hit that day, week, month etc.
It works well but I would like to add a "SUBMIT" button that when a user clicked it would send the data they have entered in specified cells to myself. I am not sure how to go about it, If needed I don't have access to systems like SQL, Visual Studio etc in work as said just basic admin job at the moment.
Would It need to be submitted as a CSV? or could it be submitted from the user's sheet straight onto another macro I have designed giving the results for the whole team? As said I am totally new to this idea.
Cheers Guys.
Awright, according to what you may need in a very simple approach, the first thing you need to do it's to know the cells where they're going to enter info (care with ranges ), let's assume for this example that whe only had one data entered in the first cell of the team worksheet. So, create a button called 'button1' or as you wish and on the click event use this code :
Private Sub button1_click()
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
End Sub
That would copy the value from one sheet to another, now, if you had you sheet locked via password, you must unlock it before doing that,then lock it again so code would be like this :
Private Sub button1_click()
On Error Resume Next
yoursheet.unprotect password:="yourpassword"
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
On Error Resume Next
yoursheet.PROTECT password:="yourpassword"
End Sub
I clarify that this is a very simple approach, so, if you're using specific cells you can copy one by one and this would do (so you can make anny calculation son your admin sheet), but when you're copying ranges should be like this :
Teamsheet.Range("A1:D3").Value = yoursheet.Range("A1:D3").Value
Also, always consider how they enter this data you need.
UPDATE :
Let's say you have a team workbook and yours is admin_workbook, concept it's similar. This code will do what you need but both workbooks should be at the same folder or path :
Private Sub button1_click()
Var_data = Teamsheet.Cells(row,column)
Application.ScreenUpdating = False
Workbooks.Open Filename:=ThisWorkbook.Path & "\admin_workbook.xls"
ThisWorkbook.Activate
Admin_sheet.Cells(destinyrow,destinycolumn) = var_data
Workbooks("admin_workbook.xls").Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
First you capture data on a var, then you open your admin book, put the data on the cell you want and close that workbook saving changes (you decide if you keep this line or mantain the workbook open and save manually). Also, Application.screenupdating it's a line that helps your screen doesn't flick when changing between workbooks.
Hope it helps friend !
My Question
I'm looking for a way in VBA to set a workbook to 'Print Workbook' rather than worksheet.
My Roadblocks
Can't use an AutoExec macro in the workbook itself, as this is a procedurally-generated .xls
I have ACCESS VBA code that exports query results into an Excel document. That same VBA code then opens the Excel document, formats the .xls file and adds a few extra things (Headers, Footers, Freezes header rows in specific worksheets, etc). Then closes the .xls until the end users opens it later.
Can't use ActiveWorkbook.PrintOut
The end user typically needs to print NOTHING, or THE ENTIRE WORKBOOK (they almost never print a single worksheet). I know I can instantly print out all worksheets by adding to the end of my sub:
ActiveWorkbook.PrintOut Copies:=1, Collate:=True
however, this is NOT what I want. I have users at multiple locations, some of which need to print, some of which don't. So I'd like to leave the option to print up to the individual users.
Thus what I'm looking to do is make it so when the end user does need to MANUALLY print the document, it is already set to print the entire workbook and not the selected worksheet. I know the user can manually do that extra click, but we've had some users just hit print and say "we're missing information" when in fact they just didn't print the entire workbook -- I'd like to eliminate this issue.
So with all of that said...
Is there a way in VBA to set 'Print Workbook' as the default print setting?
Does anyone know how to display the Last Saved Date of an Excel Spreadsheet on one of the worksheets?
I have found ways to do it using macros, but the spreadsheet is populated by an add-in called Jet Essentials, and this does not like macros so a solution here must not use one.
thought I would update on this.
Found out that adding to the VB Module behind the spreadsheet does not actually register as a Macro.
So here is the solution:
Press ALT + F11
Click Insert > Module
Paste the following into the window:
Code
Function LastSavedTimeStamp() As Date
LastSavedTimeStamp = ActiveWorkbook.BuiltinDocumentProperties("Last Save Time")
End Function
Save the module, close the editor and return to the worksheet.
Click in the Cell where the date is to be displayed and enter the following formula:
Code
=LastSavedTimeStamp()
This might be an alternative solution. Paste the following code into the new module:
Public Function ModDate()
ModDate =
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm")
End Function
Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.
Paste the following code into the cell where you want to display the last modification time:
=ModDate()
I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel
May be this time stamp fit you better
Code
Function LastInputTimeStamp() As Date
LastInputTimeStamp = Now()
End Function
and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp.
As an example in Excel file may use this
=IF(C36>0,LastInputTimeStamp(),"")
You can also simple add the following into the Header or Footer of the Worksheet
Last Saved: &[Date] &[Time]
There is no built in function with this capability. The close would be to save the file in a folder named for the current date and use the =INFO("directory") function.
I am almost completely new to using VBA and Macros on Excel 2010. I know little to nothing about macro coding, and I just started a day ago trying to pick it up.
I was asked to create a macro that copies ONLY the data from 12 workbooks and pastes it onto a blank workbook (they all have 1 sheet each, with the data on each workbook starting on cell A3 while stretching to column S (the amount of data on the sheets vary)).
NOTE: When I mean "ONLY the data," the cells that I want to be copied include the blank cells that are in between the first and last parts of the data.
1) When copying data from one workbook to another, do you HAVE to specify the cells that you would like to copy? Or is there a way to specify where the data ends on the sheet, and then copy all of that data? If so, then could someone show me how to do so? The reason for doing so is because the macro will be used weekly.
and 2) Could someone simply help me develop this macro? Help would be massively appreciated :)
Some Extra Notes:
- The Workbooks are named "Status by offering ID [1-12]
Thanks again!
Ripster has given one example of missing information from your specification.
Santosh recommends a pretty neat tool but my reading of your question is that your knowledge is not up to using a tool yet.
I deduce this is a work question and your boss has asked you to write this macro despite your knowledge of VBA being zero. This seems to be a growing problem: you can discover the answer to anything on the net so why bother with training people. Even if you produced a complete specification of your requirement, I doubt anyone will give you a complete solution. If they do provide a complete solution, it will not help with the next requirement. So I am going to break your problem down into the type of questions you can ask the net.
Each week you get 12 source workbooks and create a summary by consolidating data from the source workbooks. Do you overwrite the previous week's summary with the new summary or do you want to save all the summaries? It will not add much to the complexity to keep all the summaries but you need to decide what you want.
If you discard the previous summary, the macro can be in Summary.xlxm, say. If you save the summaries, the macro will need to be in its own workbook, Macro.xlsm say, and it will create a different summary workbook, SummaryYYWW.xlsm say, each week.
If you search for "Workbook Open" and "Workbook Create", you will find instructions on how a macro in one workbook can open other workbooks and create new workbooks.
Where are the source workbooks? Are they in the folder CurrentData which is overwritten each week? Are they in the folders Week1301, Week1302, Week1303 and so on? Are they in the folder NewData and the macro is to move them to folders Week1301, Week1302, Week1303 and so on after processing? All these are options but I suggest you start by moving the source and summary workbooks to/from a folder convenient for the macro.
Look up "ThisWorkbook" and "ActiveWorkbook". In brief: "ThisWorkbook" is the workbook containing the macro and "ActiveWorkbook" is the most recently opened workbook.
Look up workbook property "Path". ThisWorkbook.Path, for example, gives you the name of the folder containing ThisWorkbook. Look up workbook property "Name".
If the source workbooks always have the same names, you could hard code the names into the macro. I do not recommend this. Look up the function "Dir".
I hope the above has given you a start on breaking your total problem down into its components.
There are many different VBA tutorials available on the web. Try a few and pick one you like.
"Debug.Print xxx" outputs the value of xxx to the Immediate Window. This can be very helpful as you start. Try this as your first macro:
Option Explicit
Sub First()
Dim FilenameCrnt As String
Dim WbookCrnt As Workbook
Debug.Print ThisWorkbook.Name
Debug.Print ThisWorkbook.Path
FilenameCrnt = Dir$(ThisWorkbook.Path & "\*.*")
Do While FilenameCrnt <> ""
Debug.Print FilenameCrnt
If FilenameCrnt = ThisWorkbook.Name Then
With ThisWorkbook
Debug.Print " Used range: " & .Worksheets(1).UsedRange.Address
End With
Else
If LCase(Right(FilenameCrnt, 3)) = "xls" Or _
LCase(Right(FilenameCrnt, 4)) = "xlsm" Or _
LCase(Right(FilenameCrnt, 4)) = "xlsx" Then
WbookCrnt = Workbooks.Open(ThisWorkbook.Path & "\" & FilenameCrnt)
With WbookCrnt
Debug.Print " Used range: " & .Worksheets(1).UsedRange.Address
End With
WbookCrnt.Close
WbookCrnt = Nothing ' Free resource
End If
End If
FilenameCrnt = Dir$
Loop
End Sub
Best of luck
I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.
Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.
Any suggestions or ideas a very welcome.
The short story, is you can't. You might be able to do some scripting on the Excel side to format the resulting file. If you want something pretty, you probably want to create a report.
You could, instead mount the excel sheet as a table, and then on a separated sheet in the excel file, reference the first sheet, and format the second sheet for viewing.
if you use DoCmd.TransferSpreadsheet and create an original and then edit it so that the formatting is correct, you can then run DoCmd.TransferSpreadsheet again and it will update the file with the values but keep the formatting.
However, if a human then changes the file by adding new tabs, or adding calculations, etc, then the DoCmd.TransferSpreadsheet will no longer work and will fail with an ugly error message. So what we do in our enviroment is DoCmd.TransferSpreadsheet to an original file with formatting, and follow that up in the VBA by copying the file to the users desktop, and then opening that copy so the user doesn't mess up the original source excel file.
This approach is a minimum code, clean, and easy to maintain solution. But it does require a extra "source" or original file to be hanging around. Works in Access 2007.
You also would like the results to end up on a new tab. Unfortunately, I think it will take some excel automation to do that. The VBA inside Acccess can call a function inside the VBA in Excel. That VBA could then copy the tabs as needed.
My idea would be a hybrid of Excel automation from Access and creating a template in Excel as well that would have a data table linked to your query.
To start create your data table in Excel. You can start three rows down and two columns to the right if you want or wherever. Go to your data tab and click access, find your db, choose your query you want to link to, choose table as the radio button but click properties next instead of ok, uncheck the enable background refresh, this part is critical ... under the definition tab in the connection string you will see a part that says Mode=Share Deny Write change that to Mode=Read, this will make sure that the query refreshes without errors from an MS Access VBA while the db is open and will keep your users from writing back to the db in case your query is a writeable query. Once you set that up you can adjust the table formatting however you choose from the table design tab and it will keep that formatting.
For the purposes of this we are going to assume you started the table in cell B4 ,and your named the worksheet CurrentDay, for purpose of the following VBA example be sure to replace that reference with your actual placement.
Next go back to Access and write your VBA first ensure that in your VBA window you have the reference to Microsoft Excel 12.0 Object Library is selected by going to Tools > References and selecting it from the alphabetical listing.
Create your sub as follows:
Sub query1_click()
Dim xl as Excel.Application
Dim wbk as Excel.Workbook
Dim wks as Excel.Worksheet
Dim RC as Integer
Dim CC as Integer
Set xl = New Excel.Application
Set wbk = xl.wbk.Open "X:\Filelocation\FileName.xlsx" 'name and path you saved the file you previously created
xl.Visible = True
'The above is not necessary but you may want to see your process work the first few times and it will be easier than going to task manager to end Excel if something fails.
RC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("B:B")) + 3 'This will count the rows of data in your table including your header so you can copy the data to another tab dynamically as the size of your table expands and shrinks we add 3 to it because we started at row 4 and we need the location of the last row of the record set.
CC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("4:4")) + 1 'This counts the header row and adds one space because we will use this as a location holder for our copy / paste function
Set wks = xl.wbk.Worksheets.Add
wks.Name = format(date(),"MM_dd_yy") 'this will name the tab with today's date... you can eliminate this step if you just want the sheets to be the generic Sheet1, Sheet2, etc.
With xl.wbk
.Worksheets("CurrentDay").Range(Cells(4,2),Cells(RC,CC)).Copy
.wks.PasteSpecial xlPasteValues 'This pastes the values so that the table links do not paste otherwise every tab would just refresh everyday.
.wks.PasteSpecial xlPasteFormats 'This gets your formatting.
.RefreshAll 'This will refresh your table
Wend
With xl
.Save
.Close False
.Quit
Wend
Set xl = Nothing
Set wbk = Nothing
Set wks = Nothing
End Sub
That should get you to have your data to not start on A1 of your sheets, save your old data each time, and automate the steps from access.