First of all, I have searched and read similar threads and I have tried the solutions that were proposed and solved the other people's problem but it hasn't worked in my case.
I basically want to create temporary excel sheet where I want to do all the calculations in the back-end and display only the output to the user in the front-end sheet.
Can anyone tell me how do I go got creating the temporary sheets and deleting them as soon as numbers are copied in the front-end sheet i.e. the sheet that user will see.
My main motive is not let the user see the various calculations that are happening in the back-end.
you can create a temp sheet in VBA by using
Sheets.Add.Name = "Temp Sheet" or any other name really
and after you calculations done on it, delete it with
Sheets("Temp Sheet").Delete
bear in mind if your alerts are on it will prompt user to agree to delete the sheet, you can avoid that by using Application.DisplayAlerts = False before deleting and follow by Application.DisplayAlerts = True after
I'd suggest to hide one sheet to perform calculations instead of creating temporary sheet.
Let's say you have input sheet, where user input his data. Another sheet is hidden. There the calculations are performed.
How to hide Sheet?
Go to VBA Code editor window (ALT+F11). Select sheet you want to hide. In a "Properties" window choose option: SheetHidden. Now, you can copy data from hidden sheet into destination sheet via using macro.
ThisWorkbook.Worksheets("HiddenSheetName").Range("A1:C56").Copy
ThisWorkbook.Worksheets("VisibleSheetName").Range("A66:C106").PasteSecial xlValues
Note: i wrote above code straight from my head. Didn't tested!
Sample code to create temp sheet:
Sub Sample()
Dim TempSheet As Worksheet
Application.ScreenUpdating = False
On Error Goto ErrorHandler:
Set TempSheet = ThisWorkbook.Worksheets.Add
TempSheet.Visible = xlSheetHidden
'Do the calculations
Application.DisplayAlerts = False
TempSheet.Delete
Application.DisplayAlerts = True
ErrorHandler:
Application.ScreenUpdating = True
End Sub
Related
I have written a pretty elaborate code to automate 2 hours of work into less than 1 min. It works, on most days, somedays like today, the code wont work, or parts of the code wont work.
Its the most obviously simple parts of the code that doesn't work.
This is frustrating me.
To get the code to work, what I have to do would be to restart the system.
Please understand, I dont change the code at all. either before or after the error happens.
the is the code, where the error happens.
Range("Table1_2[[#Headers],[Bag No]:[Batch Making]]").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Batch Making").Delete
Sheets.Add(After:=Sheets("Sheet1")).Name = "Batch Making"
Range("A1").Select
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit
Today the error was that it would not paste what the code had selected.
please note:
It selected the set of rows and columns
It created the new sheet and selected the first cell
It tried pasting the value also, but nothing happened.
After restarting the system, code worked like a dream.
Why does this happen?? any clue ??
EDIT: Biggest issue is replicating the error, as I mentioned on some days, the code will crash, else it will run smoothly.
Every day new data is fed to the program, and its cleaned to ensure that only what the program can take is given to it and this involves removing #N/A's, #VALUE's and #Ref (this was done today also, I double checked the data after the crash)
Yet at times it fails.
I'll remove the Error Handlers and have separate code to check for availability of sheet, incase the error pop's up again, then I'll update here.
You can try below code. Using select is not the best idea in 99% of time. Also, when referencing a cell it is always good to precisely tell VBA which worksheet to use.
I would suggest to replace on error resume next clause - it disables all errors in your code and you will not be notified if something went wrong.In this case you can write a bit more code to check whether the specific worksheet exist and then remove/add it.
Sub copytable()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("worksheet_with_table_you_want_to_copy")
On Error Resume Next
Application.DisplayAlerts = False
ThisWorkbook.Worksheets("Batch Making").Delete
ThisWorkbook.Sheets.Add(After:=Sheets("Sheet1")).Name = "Batch Making"
Application.DisplayAlerts = True
ws.ListObjects(1).Range.Copy
With ThisWorkbook.Worksheets("Batch Making")
.Range("a1").PasteSpecial xlPasteAll
.Cells.EntireColumn.AutoFit
End With
End Sub
edit: Code without on error but with check wheather worksheet "Batch Making" exists and delete it if it's true
Sub copytable()
Dim wsTable As Worksheet
Set wsTable = ThisWorkbook.Worksheets("worksheet_with_table_you_want_to_copy")
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name = "Batch Making" Then ThisWorkbook.Worksheets("Batch Making").Delete
Next ws
Application.DisplayAlerts = True
ThisWorkbook.Sheets.Add(After:=Sheets("Sheet1")).Name = "Batch Making"
ws.ListObjects(1).Range.Copy
With ThisWorkbook.Worksheets("Batch Making")
.Range("a1").PasteSpecial xlPasteAll
.Cells.EntireColumn.AutoFit
End With
End Sub
Unfortunately, you don't say what your code is supposed to do but it seems that you have a template and try to create a new worksheet with a table from this template.
The problem is that the source isn't qualified. Your code copies a "Table_2" from an unspecified source sheet, then deletes the "Batch Making" tab, creates a new sheet by that name and pastes the clipboard to this new sheet. The process is slightly illogical because if the source is a sheet by the name of "Batch Making" then it takes a lot of confidence to delete the original before the copy is safely in place. But I think you have a template. Therefore there is no danger of losing data but the question arises why you make the copy before you need it. Either way, if the copy on the clipboard is lost while deleting and inserting sheets "nothing will happen", as you say.
But what should happen? I presume that you just get a fresh copy of the template, and that means that you retain the structure of the table. Therefore my code below takes a radically different approach. It doesn't delete a sheet (with the table in it) and doesn't create a new sheet. Instead it simply deletes the content of the table in the existing sheet.
Sub Snippet()
' 295
Const WsName As String = "Batch Making"
Dim Ws As Worksheet ' Sheets(WsName)
Dim Tbl As ListObject
On Error Resume Next
Set Ws = Worksheets(WsName)
If Err Then
MsgBox "Sorry, there is no tab """ & WsName & """ in this workbook.", _
vbInformation, "Missing worksheet"
Else
Set Tbl = Ws.ListObjects(1)
If Err Then
MsgBox "Sorry, there is no table on the specified worksheet.", _
vbInformation, "Missing table"
Else
Tbl.DataBodyRange.ClearContents
End If
End If
End Sub
This is done by a single line of code, to wit, Tbl.DataBodyRange.ClearContents. You could take more or different action at that point. For example, you could delete unwanted rows or add default cell content. If there is a lot of such default you might get those data (or formulas) from a template. Otherwise just add it to the code. Headers and totals aren't deleted. The table's structure remains unchanged.
Before that, in the above code, the sheet is qualified and the table. In place of the error messages you could insert code to create the tab and/or create the table.
Please observe the name of the worksheet at the top of the code. You can change that string to any other name. The code doesn't specify the name of the table. Instead, it presumes that there is only one table on that sheet and clears that one.
Trying to create a workbook that gets data from ACCESS. I can open the workbook and was adding some code to auto open in excel. But when i tried to edit it keeps telling me that I must unhide hidden work sheet. And the unhide command is grayed out. When I first set it up I selected Personal Workbook, which I think applies to any book I open. Along the way I kept deleting workbooks in order start over, so I think there is nothing really to delete. I wanted to add this code to to auto start but I can't get to the code. The follwing code is supposed to unhide all hidden workboks/sheets:
Sub Viewit()
Dim Ws As Worksheet
Application.ScreenUpdating = False
For Each Ws In Worksheets
Ws.Visible = True
Next Ws
Application.ScreenUpdating = True
End Sub
Looking for a better solution and what I am doing that is wrong.
Thanks
There is a very hidden level :
ActiveWorkbook.Sheets("sheet name").Visible = xlSheetVeryHidden
Or xlSheetVeryVisible for the opposite effect
Note this level is only controllable through vba, but functions can work with cells on very hidden sheets.
I have a load of data which I need to process. I process it by pasting the raw data into a pre-made excel spreadsheet, trimming a few rows of zeros at the bottom of the processing (not pasted in) columns, and then running a macro to remove cells with 0 in them in column P.
Each spreadsheet takes 6 sets of raw data, each in a separate worksheet. The zero-removing macro takes a while so I would like to do the pasting as a separate job if I can.
I feel like this should be pretty simple but unfortunately I only have a very basic knowledge of code. My idea so far has been to try and use AutoHotKey to record a sequence to do it, but unfortunately it is clunky and hasn't worked so far because alt-tabbing is unreliable or some other issue.
I would like to make a code which switches between windows, copying the data from one excel (tab delimited .txt) file into the main .xlsm document.
I would manually save it and then open the next 6 datasets and a blank processing workbook.
Thanks for your time x
Edit: The datasets are always called a,a1,a2,b,b1,b2. They are always located in the same folder as the data processing spreadsheet. The data processing spreadsheet is always called [processor.xlsm]
Edit2: This is where I am:
Sub ImportData1()
'Prevent windows asking about saving clipboard data
Application.DisplayAlerts = False
'select dataset a
Worksheets("SeqA Run1").Activate
Workbooks.Open Filename:=ThisWorkbook.Path & "\a.txt"
ActiveSheet.Range("A4:I1000").Copy
Windows("Surge Test Data Analysis Importer.xlsm").Activate
Range("A7").Select
ActiveSheet.Paste
''Close dataset
Windows("a.txt").Activate
ActiveWorkbook.Close
'Select dataset a1
Worksheets("SeqA Run2").Activate
Workbooks.Open Filename:=ThisWorkbook.Path & "\a1.txt"
ActiveSheet.Range("A4:I1000").Copy
Windows("Surge Test Data Analysis Importer.xlsm").Activate
Range("A7").Select
ActiveSheet.Paste
''Close dataset
Windows("a1.txt").Activate
ActiveWorkbook.Close
'(repeat several times)
'Re-enable windows prompts about clipboards etc
Application.DisplayAlerts = True
End Sub
You do not need to switch between windows. You have to get references to the worksheets, and use the references. The first thing to do is record a macro, and then do whatever you would do, manually. Stop recording, and then start modifying the resulting macro.
Then, in your macro,
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb1 = Workbooks("<The name of your target Workbook>")
Set wb2 = Workbooks("<The name of your source Workbook>")
Set ws1 = wb1.Worksheets("<The name of your target> Worksheet")
Set ws2 = wb2.Worksheets("<The name of your source> Worksheet")
ws2.UsedRange.Copy
ws1.Paste
You may need to paste at a specific location in your Target.
Repeating requires looping (e.g., For ... Next). If you provide more info on your case, it would be helpful.
Remember that assigning to a variable of type Worksheet should be preceded by Set.
I have sales global sales data in very large files which I need to filter by country and product and then analyze. Since I will need to perform this same analysis over and over again with different country/product combinations I am trying to do this with a macro.
This is what the macro does:
Open the source files with global data;
Filters the data;
Copies it and pastes it into a workbook which houses the macro;
Recalculates and refreshes the workbook and;
Saves a copy of the file to another folder.
The macro appears to run fine and the files are being saved, however I am running into 2 problems on steps 4 and 5:
The pivot tables do not seem to be refreshing - this may be because the second problem:
All pivot tables in the saved copy still refer to the original file
I'd prefer to fix both problems by generating the copied file without links, but I'm also open to any bandaids that might allow me to force the copied file to link to itself (this doesn't seem to work when I do it manually).
I have the full code if you want to see it all, but because I suspect the issue is in how I'm saving the file I'll just paste that piece here. Let me know if you need to see another part of the macro. Any help would be much appreciated, thanks in advance.
Save Function:
Public Sub SaveAsCopy(filePath As String)
Dim updateStatus As Boolean
'Check current status of Alerts
updateStatus = Application.DisplayAlerts
'Turn off alerts
Application.DisplayAlerts = False
ThisWorkbook.Sheets.Copy 'creates new workbook without macros"
'The New workbook copy is now the Active workbook
'Delete Control Sheet
ActiveWorkbook.Sheets(1).Delete
'Save Macro free version and close
ActiveWorkbook.SaveAs Filename:=filePath, FileFormat:=51
ActiveWorkbook.Close
'Revert back to origional alert status
Application.DisplayAlerts = updateStatus
End Sub
Function Call:
Call SaveAsCopy(filePath)
Will share the workaround I developed since I didn't get any bites on a more elegant solution:
Public Sub SaveAsCopy(filePath As String)
Dim updateStatus As Boolean
'Check current status of Alerts
updateStatus = Application.DisplayAlerts
'Turn off alerts
Application.DisplayAlerts = False
'Hide Control Sheet
ActiveWorkbook.Sheets(1).Visible = False
'Save Macro free version and close
ActiveWorkbook.SaveAs Filename:=filePath, FileFormat:=52
'Unhide
ActiveWorkbook.Sheets(1).Visible = True
'Revert back to original alert status
Application.DisplayAlerts = updateStatus
End Sub
At the end of the parent function I close the current file, reopen the original, and loop through the new workbooks to remove macros.
I am trying to write a VBA macro to track changes to a workbook in a separate sheet.
If you do this manually, the sequence of commands is Tools > Track Changes > Highlight Changes, taking the option Separate Worksheet. You have to do two iterations of the command, one to activate tracking inline, a second to move the tracking to a separate sheet.
Using the macro recorder, I got to this piece of code:
With ActiveWorkbook
.Save
.KeepChangeHistory = True
.HighlightChangesOptions When:=xlAllChanges
.ListChangesOnNewSheet = True
.HighlightChangesOnScreen = False
.Worksheets("History").Select
End With
When I run this, I get the error HighlightChangesOptions method fails. Any suggestions?
The HighlightChangesOptions method will only work if the workbook is already shared. In the UI, turning on HighlightChange will share the workbook automatically, but not so in VBA.
Application.DisplayAlerts = False
With ActiveWorkbook
.SaveAs , , , , , , xlShared
.KeepChangeHistory = True
.HighlightChangesOptions When:=xlAllChanges
.ListChangesOnNewSheet = True
.HighlightChangesOnScreen = False
.Worksheets("History").Select
End With
The DisplayAlerts call will prevent Excel from warning you that you are overwriting an existing workbook - itself. You may want to comment that line out just to see what's going on.
Note that this code cannot live in the shared workbook. Once you share the workbook, the code stops executing and errors. It has to live in a different workbook or add-in.