Is it possible to always stay in activesheet when hiding another? - excel

I have created a dynamic workbook where i put and pull data to more sheets containing data from other sources. I have a "Temp" sheet where code updates som data, this sheet is hidden until the macro is run, to put and pull data, i make it visible and when finished i hide it again. This works (almost) perfect.
The problem occurs when i hide it, then my last Sheet i selected automatically? My code is totally without any .select or .active (Still learning) because it is important that code always return to the sheet from where the code is run as this changes name everyday.
I can't seem to find anything that solves my issue, hope somebody can help:
I tried the following, as you can see in the following code:
Sheets("Temp").Cells.ClearContents
Sheets("Temp").Visible = False
'Cleans filters
ActiveSheet.ShowAllData
Application.Goto Range("A4")
Application.ScreenUpdating = True
I want to always stay in my activesheet (example: ("16") which is the actual date, there will be one sheet for everyday etc. ("17"), ("18") and so on.)

You can use With to immediately reactivate the sheet, like so:
With ActiveSheet
OtherSheet.Visible = xlSheetVisible
.Activate 'Immediately reactivate the ActiveSheet
End With
(You may want to toggle Application.ScreenUpdating so that you do not see so much as a flicker of the other sheet)
However, why do you need to show the sheet to copy data from it? If you are not using Select (which you say you are already sorted on), then you should be able to do most things with a Hidden sheet, such as HiddenSheet.Range("A1:B3").Copy
(A "Very Hidden" sheet, on the other hand, has a couple of restrictions - for example, you cannot delete a Very Hidden sheet.)

Related

Hide or unhide Excel sheet but formulas should work

I have used this method before but after six months I cannot.
I created data entry fields through which I move data from Sheet1 to Sheet2 using a button.
I do not want users to see Sheet2 so that they cannot change anything. I was using the formulas below.
Sheets("Data Sheet").Visible = True
Sheets("Data Sheet").Visible = False
After hiding the sheet I protect them with the password. The main advantage of code is that I can still post the data from Sheet1 to Sheet2 after hiding.
Upon research I found one more formula to hide the sheet but after hiding sheet2 posting via Sheet1 to Sheet2 (which is hidden) gives an error.
ThisWorkbook.Worksheets(Array("Data Sheet")).Visible = xlSheetHidden
How can I hide Sheet2 and continue posting the entries via Sheet1.
You can manipulate data on a hidden sheet, no need to unhide it.
Unless you are trying to select cells, but you shouldn't have to do that.
You do however need to unlock a sheet before editing it if the cells are protected. You can do this as part of the process.
Sheets("Data Sheet").Unprotect Password:="pass"
----
whatever code you have
----
Sheets("Data Sheet").Protect Password:="pass"
You do might want to have some error handling in there however, since if the code throws an error, the sheet will be left unlocked.
a) The statements Sheets("Data Sheet").Visible = False and ThisWorkbook.Worksheets(Array("Data Sheet")).Visible = xlSheetHidden do basically the same. However, you will need to understand why it is important to qualify the Sheets: ThisWorkbook.Worksheets will access the worksheets from the workbook where the code lives in, just writing Sheets (or Worksheets) will access the sheets of the ActiveWorkbook - and that may be a different workbook. The Array("Data Sheet")-part is unnecessary in your case (you can pass an array of sheet names to hide more than a sheet at once). Setting visibility to xlSheetHidden or to False is identical.
b) Hiding a sheet and protecting a sheet are two different, independent things. You can protect a sheet but not hide it, you can hide a sheet but let it unprotected.
c) The main idea of protecting a sheet is to allow user input only at specific cells. The user can change the content of the sheet, but only to cells which are not formatted as "Locked".
d) If you protect a sheet via Excel (no matter if hidden or not) and want to modify something via code, you will need to unprotect it (and protect it again after the code is done). However, when protecting the sheet via code, you can specify that you want to allow the code to make modifications by setting the UserInterfaceOnly-parameter:
Thisworkbook.Sheets("Data Sheet").Protect Password = "IWontTellYou", UserInterfaceOnly:=True
e) If you never want to show the sheet, set the visibility not to hidden, but to veryHidden. With that, the sheet cannot be made visible by the use from within Excel: It will not be listed under "Unhide..." - in that case there is not need to protect it.
Thisworkbook.Sheets("Data Sheet").Visible = xlSheetVeryHidden
(Note that in that case you can make the sheet visible again only via code, but a one-liner in the immediate window is sufficient)
You will have to write a code to first unprotect sheet2, then paste the data and protect sheet2 again.

Macro in Excel to Copy/Paste Specific Ranges in Two Workbooks into a New Workbook (More Details Inside)

I can perhaps better describe what I want by way of example. I have two Excel workbooks. I want to essentially copy one over to a new workbook as it is (basic copy/paste of everything), and then copy over a specific portion of the other workbook and paste it at the end of the new workbook.
So, there are two input workbooks and one output workbook. And that is how I would like the macro to be structured: There should be a "master" workbook that contains the macro (button) where the two input workbooks are specified by their folder path, and there is an output folder for the new combined workbook (see the very end for example of how I'd like it specified). The first of the input workbooks should have everything in it copied over. Note that this should be dynamic, and should not dictate a specific cell range (as cell ranges could vary). An example of the first input workbook is shown below:
Everything is to be copied over. I don't think that's much of an issue. The tricky part (for me) is to then take a specific portion of the second input workbook and copy/paste that to the end of the first input workbook. I am finding this difficult because the second input folder should be selected by a specific header and then everything under that header should be copied (i.e. select header and then CTRL+SHIFT+DOWN). For example:
This should take "Maturity[5,)" (highlighted in yellow) as the header and then select everything under that, copy it, and then paste it to the matching header at the end of the first input workbook (second row, i.e., Row 8, which, by the way, is the format for all workbooks for this: Rows 1:6 are empty, but should stay like that).
Hopefully you're still with me. After this is done, the new (combined) workbook should look something like this:
Just even getting this far would be extremely helpful. But there is one more issue. By copying over the entirety of the first input workbook, there is an additional header (Row 7; "L-OAS" in the above picture). This header needs to be merged and centered across the range of the new combined workbook, including the second input workbook portion added:
And that's it. Once that header has been merged and centered in the new workbook, the macro should save the new workbook in the output path specified.
Example of input/output paths to be specified:
EDIT: The below is my attempt at doing part (1) -- that is, just copying and pasting the first workbook.
Sub Combine()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim wsSource As Worksheet, ws As Worksheet
Application.ScreenUpdating = False
shtOutput1.Visible = xlSheetVisible
shtOutput1.Cells.Clear
Set outputRange = shtOutput1.Cells(1, 1)
Set wb1 = Workbooks.Open(Range("USDInputFile1").Value, False, True)
For Each wsSource In wb1.Worksheets
If InStr(wsSource.Cells(1, 1).Value, "Bloomberg") > 0 Then
With wsSource
wsSource.Copy shtOutput1
End With
End If
Next
wb1.Close False
Application.ScreenUpdating = True
With Workbooks.Add
shtOutput1.Copy .Worksheets(1)
Application.DisplayAlerts = False
For Each ws In .Worksheets
Next ws
Application.DisplayAlerts = True
.Close True, ThisWorkbook.Names("OutputFolder").RefersToRange.Value + Application.PathSeparator + "USD Combined Output.xlsx"
End With
shtOutput1.Cells.Clear
shtOutput1.Visible = xlSheetHidden
End Sub
"shtOutput1" is a worksheet in the master workbook (where the macro
button and file paths are located
"USDInputFile1" is a named Cell in the master workbook that leads to
the file path for the first input workbook (i.e. "wb1" -- "wb2" will
be the second input workbook)
Lets just take a step back and look at this from a scalability stance.
You don't want a button to combine things because there is a lot to go wrong and a fair bit of babysitting you will have to do VBA wise and on top of that pressing is a button... ppffft that's work...
No what you want is a seamless update where anything added to Maturity 5 or Maturity 10 will automatically update to your output leaving them to just grow on their own untouched downward like Microsoft intended.
First lets look at the structure, there is some, they have headers but they are not tables and they both have a common ID Date, So change your bottom most headers to ensure they make sense and are Uniform, Unique and Consistant across all iterations of each table. So Mat5_Total or Mat10_Total etc for however many you have.
Insert Tab - Table - Give them proper Shorthand Table names like tblMat10 and tblMat5
Lets open a New File and get them in with Data Tab in the ribbon - External Data - Tranform - Little Down arrow on Close an Load and you only want this in the datamodel not loaded to the Spreadsheet So check Create Connection Only and Add this data to the Datamodel. Uncheck everything else there is no need to clutter your output.
Repeat 3 but for Mat10 only when you get to Close an load instead look to the Right and hit the down arrow on Merge Queries - as a new Query .
Now a new window will pop up Select the two queries and Join them on their Dates as the ID
Now you can close and load to the a sheet.
Give it a spin add some new data to Mat5 or Mat10 and refresh your newly created linking Sheet.
This works for all kinds of data, you can trial this with stocks, shares, CSV, ODBC Connections all sorts of data connections. all you need is a properly formatted infrastructure aka properly formatted tables!
A bonus to this method is if the tables evolve, modifying your Power Query is easy. Just rememeber to go into your connection settings and select refresh on open and if you like set it to refresh every 5 minutes.
7 Optional Bonus - Once this output table has been made it will be compatible with any external programs, because it is a correctly formatted output table.

Locking specific cells and creating a summary sheet

I have a workbook I'm trying to create a vba code for but I keep running into different errors...runtimee error, object error etc
I have created a series of forms and I need to lock the cells that contain specific texts. The forms ask a series of questions, including First name, Last name and Degree. I need to lock the cells containing these texts but leave those that will contain the responses open.
Also, I need the responses for the cells containing Degrees and location to feed a summary sheet.
The closest I got was using an If function but it didn't quite cover everything I wanted to do. Please help if you can.
If you are using User Forms to collect the data then you are likely using VBA to transfer the user form data to te worksheet. If the worksheet is protected with the UserInterfaceOnly:=true argument, you can do anything you want with the worksheet's data (e.g. add/revise/delete/etc) through VBA and the user cannot make any modifications.
Run this once.
sub allowVBA()
with thisworkbook.worksheets("sheet1")
.unprotect password:="password"
.protect password:="password", userinterfaceonly:=true
end with
end sub

Is there an easy way to copy the ActiveSheets .PageSetup?

Seems simple and probably a case of "It's monday" but I can't find the answer to this.. without having to record all the pagesetup variables in strings beforehand, is there a way to copy a worksheets .pageSetup property?
in a macro im running, I create a new page, paste some data, change a bunch of pagesetup settings, then print. I was hoping there was a way i could save the page setup before hand, and apply it again afterwards so my users don't have to worry about fixing settings ever.
I tried:
dim ws as worksheet
set ws = ActiveSheet.pageSetup
'settings change / print
ActiveSheet.pagesetup = ws.pagesetup
that doesnt work because ws.pagesetup is now linked to activesheet.pagesetup, so as soon as i change the active sheets settings, ws's settings get changed too.
I also tried set ws = sheets(1) because the new page is never the first page, but then with that one ActiveSheet.pagesetup = ws.pagesetup doesnt work either, it says object doesn't support this property or method
Is there a simple way? must I have 20 different string variables to hold all the current pagesetup variables?
Thanks
When I want to accomplish something like this I'll save all my formatting and pagesetup stuff to a hidden sheet. At the right time I'll have my code copy and paste everything where I need it. In this case it would probably be easiest to start by making a copy of the hidden sheet. Then dump in your data and work from there.
Rather than coping page setting from a master sheet to other sheets:
Create the master sheet
Establish the page settings for this single sheet
Make copies of the master
Populate the copies with data, formulas, etc.
In other words, anticipate your needs and setup the sheets in advance.

Protected Sheet Warning On Any Edit

Hoping to get some help with Excel 2010.
I have three visible sheets. On Workbook Open, vba password protects each of the three sheets.
Now, whenever I make a change to any unlocked cell in any sheet, I get 4 protected sheet warning pop-ups. The one that says that the cells are locked and you have to unprotect to edit? That's all well and good except that I am not editing locked cells. I am editing unlocked cells in other sheets!
Has anyone had this experience? I have played around and two of them can be attributed to each of two sheets. That is to say, when I only protect the first sheet, I get no pop-ups, when I protect only the second, I get 2 and when I protect only the third, I get 2.
Taking out formulas hasn't made a difference.
Here is the code for the locking:
For Each wSheet In Worksheets
wSheet.Unprotect Password:="JMP_DST_Lock"
If wSheet.Visible = True Then
wSheet.Protect Password:="JMP_DST_Lock", UserInterFaceOnly:=True
wSheet.EnableOutlining = True
End If
Next wSheet
ThisWorkbook.Protect Password:="JMP_DST_Lock"
Thank you very much for any help.
EDIT:
Turns out the comboboxes are the reason for the error. If the linked cells are locked, anytime the sheet calculates (any change when on automatic calculation) causes the warnings. Now, I have code that unprotects the sheets on each combobox GotFocus, but aside from that, these are cropping up.
Is there a middle ground? A way to keep the linked cells locked without these warnings popping up? A way to make sure the comboboxes are hitting the linked cells except on selection?
Thank you!
Your logic seems wrong. You're unprotecting the sheet, then protecting visible sheets, and then protecting the entire workbook (in the last code line).
Try something like this instead (untested):
For Each wSheet In Worksheets
If wSheet.Visible = True Then
wSheet.Protect Password:="JMP_DST_Lock", UserInterFaceOnly:=True
wSheet.EnableOutlining = True
End If
Next wSheet
If the workbook is saved with the sheets in protected state, change it to something like this instead:
For Each wSheet In Worksheets
If wSheet.Visible = False Then
wSheet.UnProtect Password:="JMP_DST_Lock"
End If
Next wSheet

Resources