Can I set a cell in a sheet as the selected one, without activating the sheet? - vba

In a workbook I am creating I have created a procedure which loops through several worksheets clearing out some ranges++, preparing the workbook for a new year. However, I wanted to set a given cell in the sheet, e.g. F5 as the active one before moving on to the next sheet, as that's where it's most likely the users will start inputting data when they move to the sheet.
However, trying to put both .Select and .Activate into line 5 of the code below fails with Select / Activate method of Range class failed.
For Each ws In ThisWorkbook.Worksheets
If InStr(1, ws.CodeName, "Veke_", vbTextCompare) > 0 And Len(ws.CodeName) = 7 Then
Call lås_opp_ark(ws)
Call oppdater_ark_for_nytt_år(ws, førsteSkiftIVeka(dato))
ws.Range("F5").Select
Call lås_ark(ws)
End If
Next ws
Trying to figure out why this didn't work I eventually came across this documentation-page from Microsoft which states that:
Before you can use the Selection property successfully, you must activate a workbook, activate or select a sheet, and then select a range (or other object) using the Select method.
Which I take to mean that using Select on anything but the active worksheet won't work. The page doesn't explicitly state anything about Activate, but I assume the reasons for the errors I'm getting to be the same.
Now, my question is this - is there any way to set the active cell in a nonactive worksheet without activating it first? If not, would activating each sheet in the workbook to set the active cell be very resource intensive? I guess I could check the latter myself, but any input would be interesting too.

No need to select the cell, instead activate it. Try this:
Replace:
ws.Range("F5").Select
with this:
Application.Goto ws.Cells(1), 1 'This activates ws and scrolls to place cell `A1` at the top of the window
Application.Goto ws.Range("F5") 'This selects Cell `F5`
see Application.Goto Method (Excel)

Related

Excel VBA - Loop not adding autofilters to my worksheets

I have some code that (should) loop through all my worksheets and add an autofilter, however for some reason they're not showing up. When I turn on events, I can see that it is quickly being added then removed almost instantly. I'm assuming that this is because of something written earlier in my code, but I have too much code before this to evaluate what is causing the issue... Is there something I can add to guarantee the filters are added? Code:
Dim wsfixer As Worksheet
For Each wsfixer In ActiveWorkbook.Worksheets
With ActiveSheet
.AutoFilterMode = False
.Range("A:S").AutoFilter
End With
On Error Resume Next
Next
If you want to process the code on each worksheet, change
With ActiveSheet
to
With wsfixer
By using With ActiveSheet the code within the With block is being "shortcutted" to using the active sheet (e.g. .AutoFilterMode is treated as ActiveSheet.AutoFilterMode). So you are executing the same code over and over to the one active sheet.

Range SpecialCells ClearContents clears whole sheet instead

I have a sheet in Excel 2010 which is setup as a pseudo form (I didn't create it, I'm just trying to fix it) so formatting suggests that the user can only enter in certain cells. Depending on certain functionality these areas need to be reset, i.e. cleared although formulae and standard/conditional formatting need to be kept. I have defined each of these cells/ranges as named ranges so I can easily loop through them using the following code: -
Public Sub ResetDetailSheet()
Dim nm As Name
With ThisWorkbook
For Each nm In .Names
If Left(nm.Name, 9) = "nmrDetail" Then
Range(nm.Name).SpecialCells(xlCellTypeConstants).ClearContents
End If
Next
End With
End Sub
For some reason instead of clearing the constants from the specific range it is clearing constants from the entire sheet so I am losing all titles/headings. Formulae and standard/conditional formatting are staying as expected.
What am I doing wrong?!?!
As a test using the immediate window I tried clearing a specific cell, e.g.
Range("G7").SpecialCells(xlCellTypeConstants).ClearContents
But this still cleared all constants from the entire sheet.
What am I missing? I don't understand. Maybe I'm being dumb.
Sorry, I can't upload an example. This place is pretty locked down.
Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
So, make sure your range has more than a single cell before you clear it - if the range is only a single cell, then check if it .HasFormula; if that's the case then its .Value isn't a constant:
With ThisWorkbook
For Each nm In .Names
If Left(nm.Name, 9) = "nmrDetail" Then
If nm.RefersToRange.Count > 1 Then
nm.RefersToRange.SpecialCells(xlCellTypeConstants).ClearContents
ElseIf Not nm.RefersToRange.HasFormula Then
nm.RefersToRange.ClearContents
End If
End If
Next
End With
Note that I'm using Name.RefersToRange instead of fetching the range by name off the active sheet.

Excel VBA Allow user to select an already open workbook and attach variables to selected workbook

With Excel 2013 VBA, I am familiar with setting the value of a Workbook variable with:
Set oWBSource = Workbooks.Open(strFileToOpen) 'Works well.
In my situation though, sometimes the Workbook is already open on the desktop. I am trying to find a more elegant way to "select" that spreadsheet and then attach my variable to that workbook to operate on. The code is running on a separate "master" spreadsheet.
Currently, I am asking the user if the file is already open. If so, then:
Dim rng As Range
Set rng = Application.InputBox("Select any cell on workbook to operate on.", "Click Workbook Cell", Type:=8) 'Stops code and allows user to select a cell on an open spreadsheet
Dim sTest As String 'variable used to test.
sTest = ActiveCell.Value 'Testing to see what value code is seeing.
sTest = ActiveWorkbook.Name 'Testing to see what value code is seeing
Set oWBSource = Workbooks(ActiveWorkbook.Name) 'Works if selected Workbook is maximized and minimized.
If I run the above code and when it runs the inputbox, if I click one cell on the spreadsheet I want the code to operate on and allow the code to continue, the variables still reference the Workbook where the code resides rather than the "selected" workbook. If, while selecting one cell, I also maximize and minimize the spreadsheet (basically Activate it) and then click a cell and allow the code to continue, the active spreadsheet is set and it seems to work. I realize the cell reference is doing nothing. But the pause allows me to "Activate" the desired spreadsheet.
I am looking for a more elegant way to handle attaching my code to an already open spreadsheet. My current solution is clunky. Isn't there a way to have the user select the open spreadsheet and then have my code "act" on that spreadsheet?
I know this is a weird question. Be kind rating it please??!!
If I understand correctly what you're trying to do, just use the rng to resolve the selected Workbook:
Set oWBSource = rng.Parent.Parent
rng.Parent is the Worksheet a Range is a part of, and the .Parent of a Worksheet is its Workbook.

VBA code that runs like goto functions: "Ctrl-[" and "F5"

Is there any VBA code that simulates the normal goto Excel function Ctrl+[ and F5?
Further elaboration with an example:
In this Problem.xlsx are two worksheets—Alpha and Beta.
I would like a code to
Do a Ctrl+[ on cell A2 of the Alpha worksheet (i.e. grab the Beta!B5 reference in the cell)
So as to jump to cell B5 of the Beta worksheet (using the Beta!B5 reference, make the jump)
Move one cell to the right, i.e. C5 of the Beta worksheet and shade that cell yellow
And finally do a F5 to go back to cell A2 of the Alpha worksheet
I have Googled for 2 hours on various keywords like goto, ctrl-[, F5, previous selection, etc. to no avail.
Additional note:
I am trying to simulate the goto functions Ctrl-[ and F5 such that any active cell (with a link to another cell in another sheet) I am on, the VBA code can perform the jump, do the color shading and jump back to the original sheet. i.e. the below codes are too restrictive
Sub JumpColourJump()
Worksheets("Beta").Range("B5").Offset(, 1).Interior.Color = vbYellow
Worksheets("Alpha").Range("A2").Select
End Sub
The code should be flexible to jump to whichever sheet in the same file or in another file that the active cell is referring to.
Most of your code can be produced by recording a macro, but the more complex parts appear to be:
Navigating to the first cell which references the selected cell - this post on superuser looks like it contains some good advice
Returning to the previous sheet - you could just take a reference to the active sheet at the start of your function, then restore it afterwards, i.e.:
Dim initalSheet As Worksheet
' Take a reference to the current sheet
Set initialSheet = ActiveSheet
' *** Perform changes here ***
' Return to the initially selected sheet
initialSheet.Select
Something like this in order to go back and forth between the pages will work.
'follow local hyperlink
Application.Goto Reference:=Worksheets("Alpha").Cells(1, 1).FormulaR1C1
'color the cell to the right
ActiveCell.Offset(0, 1).Interior.Color = vbYellow
'return using the same method
You can then use ActiveCell.Offset(row, col) to get the right cell and perform the operations, and return using the same method.
In order to return to the previous location, you could save it in a variable,
Dim returnSheet As String, returnCell As String
returnSheet = ActiveSheet.Name
returnCell = CStr(ActiveCell.Address(False, False))
'Jump to cell, do your magic
Application.Goto Reference:=Worksheets(returnSheet).Range(returnCell)
or for several jumps from cell-to-cell a class-module acting like a stack implementing push & pop functions would be ideal.

How do I open a worksheet in vba?

Hilariously the following code only works if the worksheet is actually selected in the excel window. I really want to finish this macro soon but can't seem to work out how to select a specific worksheet so it is open in excel? Many thanks if someone knows how. I have to use range and so on.
sheet.Range(Cells(firstRow, 2).Address(False, False), Cells(lastRow, 50)).Select
With Selection
.Copy
End With
sheet.Range(Cells(firstRow, 3).Address(False, False), Cells(lastRow, 51)).Select
With Selection
.PasteSpecial xlPasteValuesAndNumberFormats
End With
You can activate the worksheet by name or by 1-based index (the number -- 1st workbook, 2nd, and so on). The syntax is the same, either way.
This will activate the 3rd worksheet:
ActiveWorkbook.Sheets(3).Activate
This will activate the worksheet named stats:
ActiveWorkbook.Sheets("stats").Activate
Of course, you don't have to actually make the worksheet selected in the Excel window to work with it. Your code uses a variable called sheet, which I assume you've assigned to the active worksheet. Instead of doing that, you can set sheet = ActiveWorkbook.Sheets("stats"), and then work with the sheet even if is not in view.
Workbooks(x).Worksheets(x).Activate ?