Get visible row and column number - excel

I have a simple macro at my Excel worksheet, which does some simple calculation.
What happens is that for a better user experience I want the macro to run and when it is finished to return to the cell that the user was before he activated the macro, so that the user won't see any change on the screen.
Ok, so that's not to hard:
Dim activeRow As Integer
Dim activeCol As Integer
Sub myCode
activeRow = ActiveCell.Row
activeCol = ActiveCell.Column
' code...
Cells(activeRow, activeCol).Select
End Sub
The problem with the code above is that the line and columns that were visible before the macro runs are not the same on the end, because the macro may have scrolled the worksheet to the left, right, up or down.
For example, you can see the cell E26 on your display either if the first line visible at your worksheet is 15 or 16.
So the question here is how can I know the line and column number that are visible at the user display?
I was wondering that would be something like:
Dim topLine As Integer
Dim bottomLine As Integer
topLine = ActiveWorksheet.GetVisibleGrid.TopLine
bottomLine = ActiveWorksheet.GetVisibleGrid.BottomLine

re: "... for a better user experience I want the macro to run and when it is finished to return to the cell that the user was before he activated the macro, so that the user won't see any change on the screen."
The easiest way to do this is never use .Select or .Activate. There are less than an isolated handful of circumstances where using .Select is preferable to direct cell and worksheet reference(s) and only half again of those are actually necessary.
See How to avoid using Select in Excel VBA macros for methods on getting away from relying on .Select and .Activate to accomplish your goals.
Get started converted your code to eliminate .Select and .Activate. If you run into problems, post your working code here or at Code Review (Excel). If it is more than a page or so, post sections of it.

Here is one approach. What I have done is to save the active cell. freeze panes there, then return to that cell at the end and unfreeze panes.
Dim cell As Range
'save current cell and freeze panes here
Set cell = ActiveCell
ActiveWindow.FreezePanes = True
'go somewhere way off screen
Range("A1").Select
'now go back and remove freeze panes
cell.Select
ActiveWindow.FreezePanes = False

Related

How to jump to a specific cell based on the list selection

I have created a drop-down list in cell R5 containing names, lets call them Name1 Name2 Name3. I'd like when the user selects a certain name the sheet will scroll down to a specific row. For instance, if Name 1 is selected I'd like it to go to row 2, if Name2 is selected row 10, and Name3 row 18. The list is on the same worksheet as the data I'm wanting to scroll to. Is there some code I can use to do this?
You would need to use Sheet Events to handle this. Something like this:
In your Worksheet Module of the worksheet that has your input range, put this code
Private Sub Worksheet_Change(ByVal Target As Range)
Dim InputRange As Excel.Range
Set InputRange = Me.Range("R5")
'// Check if the change is happening in your dropdown cell
If Not Intersect(Target, InputRange) Is Nothing Then
Select Case InputRange.Value
Case "Name1"
Application.ActiveWindow.ScrollRow = 2
Case "Name2"
Application.ActiveWindow.ScrollRow = 10
Case "Name3"
Application.ActiveWindow.ScrollRow = 18
Case Else
'//...
End Select
End If
End Sub
Edit:
If you're having trouble getting this to work. Try adding a breakpoint by clicking in the area to the left of the code. A breakpoint will halt execution when the flow of code reaches that point. This is one way to figure out if Excel is even TRYING to run this block of code.
Debugging Excel Code
Say we put a little jump table in columns S and T like:
The row numbers are in column T. We put the drop-down in R5 and the following code in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim R5 As Range, v As String, r As Range
Set R5 = Range("R5")
If Intersect(Target, R5) Is Nothing Then Exit Sub
v = R5.Value
Set r = Range("S:S").Find(what:=v, After:=Range("S1"))
Application.Goto Range("A" & r.Offset(0, 1).Value)
End Sub
Whenever the user picks a new name in cell R5, the code will jump to the row listed in column T.
Because it is worksheet code, it is very easy to install and automatic to use:
right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE windows as above
clear the code out
close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!
Right click on the cell. At bottom of the popped up window you find "Hyperlink". Click it. Another window opens. There select the sheet and enter the cell number where you want to go. That's all. In this cell the address given under hyperlink appears. If you give a name to it that name appears. Thereafter whenever you click on this cell/name in this sheet you go to the cell in the sheet specified under "Hyperlink". You can enter data in the new place. But you won't be able to come back to this cell on pressing enter. When you press "Enter" in the new place you go to the next cell in that sheet as usual. I used another hyperlink to come back. It is working for me. I Hope this is a facility provided by excel for jumping easily to a new location based on the hyperlink. Hope there won't be any cascading effect. I hope this is exactly what you wanted.
Press TAB on your keyboard. It might work. Just try it.

How to filter based on clipboard in Excel using VBA?

I work with a bunch of people in my department and always share my code with them so you'll be helping me and my coworkers as well!
Using the macro recorder I have created this code to filter the column I want filtered, but I need to change the code to filter it based on what ever is on the clipboard (what ever cell I pressed Ctrl+C on previously). I pressed Ctrl+C while recording the macro but it didn't record those button presses, it only pasted what was in my clipboard at the time into the macro.
Sub Filter()
ActiveSheet.Range("$A$1:$V$12955").AutoFilter Field:=2, Criteria1:= _
"Clipboard"
End Sub
This is one of the First Projects That I did in Excel. I will explain How my code is working, then you can manipulate this according to your need.
Youtube Link on How to Use it
After Pasting the code in your Personal Macro, Create a Shortcut on the Quick Access ToolBar for this Macro.
Then All you need to do is, Apply Autofilter on the Range you want to Filter, Copy the Cell or the Range of Cells that contains the value you want to filter, and select the header of the column on which you want to apply this Filter. Press the Created Shortcut.
It will work on the Single Cell Also, So you don't need to amend it. Just follow the Instructions Above.
Here Is the Code:
Sub filtrr()
'
Dim i As Integer
Dim Test As String
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
Test = clipboard.GetText
Test = Replace(Test, Chr(13), "-")
Test = Trim(WorksheetFunction.Clean(Test))
Dim ab() As String
ab = Split(Test, "-")
ReDim Preserve ab(UBound(ab) - 1)
ActiveSheet.UsedRange.AutoFilter Field:=Selection.Column, Criteria1:=ab, Operator:= _
xlFilterValues
End Sub
In your case it's only One cell that contains value, but this code is a life saver if you want to filter like 50 values in a table of thousands of values.

Automatically delete the formula once I get the value in Excel?

Is that possible to do such a thing in excel?
I have been searching for many articles and videos
and all those are telling me to do it by hands
so, I wonder if there is any way to immediately delete the formula and keep the value? so that the links between the old and new value can be eliminated?
Like, I don't know, maybe =sum(A1:A5,del)
something like this?
Is there any way to immediately delete the formula and keep the value?
No
However, you can do so with vba. This is quite a simple code, which would check whether the value of ActiveSheet of Range("A1") is more than 0. If it is, it saves the cell as a value and the formula disappears. Just be careful, you cannot use "Undo" once you run the code:
Sub DeleteValue()
With ActiveSheet
If .Range("A1").Value2 <> 0 Then
.Range("A1").Value2 = .Range("A1").Value2
End If
End With
End Sub
Say, for example, we are entering items in column C. If we enter a formula in a C cell, we want the formula to be automatically converted to value. Enter the following event macro in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rInt As Range, r As Range, C As Range
Set C = Range("C:C")
Set rInt = Intersect(Target, C)
If rInt Is Nothing Then Exit Sub
Application.EnableEvents = False
For Each r In rInt
If r.HasFormula Then
r.Value = r.Value
End If
Next r
Application.EnableEvents = True
End Sub
Because it is worksheet code, it is very easy to install and automatic to use:
right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE windows as above
clear the code out
close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!
Automatically? No.
Manually? Yes.
Select the cell range where you want to delete the formulas and keep only the values, copy them, then right click -> Paste Special -> Values (V).
This will replace the cell formulas with the cell values that the formula calculated (at the moment you copied them).

How to update cell references when moving cells into same sheet as target?

How do you force an excel workbook to use itself as a source for worksheet links?
I'm writing a VBA macro to automate the process of adding an excel worksheet into a workbook. The worksheet (sheet1) takes only certain (but very many) responses from within the several sheets (response1, response2, response3) of the questionnaire. As a result of this, sheet1 contains lots of cell references that don't lead anywhere until after the macro is run.
For instance a1 in sheet1 "='response1'!b6". This returns a #REF! error before the macro is run (which is fine).
After the macro is run sheet1 is now inside the correct workbook, and "='response1'!b6" is now a valid cell reference.
Except excel doesn't realise this until after I manually click the cell in Sheet1, press f2, then press enter. When I do this the cell is correctly populated. The trouble is there are large numbers of cells.
Is it possible to construct a VBA macro that will simulate this process of selecting formula boxes and pressing "Enter". Looking up people with similar problems, most have had the problem remedied by some combination of f9, turning automatic calculation back on, or ActiveSheet.Calculate or a variant. None of these have worked, it appears to be an issue with references, even though the references point to valid locations.
Otherwise, is it possible to use VBA to perform the same process as:
Data > Edit Links > Update Values
But in this case we'd need to specify the currently opened workbook as it's own source. Is there any way to do this?
When I manually selected the current workbook as the source under "Edit Links > Update Values" excel strangely repeats the worksheet name in the cell references, like this: "='[response1]response1!B31", which then fails to update when cell b31 changes, so this is not a solution.
Here's the code that runs on button press:
Private Sub CommandButton1_Click()
'copy worksheet into responses
Dim CopyFromWbk As Workbook
Dim CopyToWbk As Workbook
Dim CopyToWbk As Workbook
Set CopyFromWbk = Workbooks("Addition.xlsm")
Set ShToCopy = CopyFromWbk.Worksheets("Sheet1")
Set CopyToWbk = Workbooks("QuestionnaireResponses.xlsm")
ShToCopy.Copy After:=CopyToWbk.Sheets(CopyToWbk.Sheets.Count)
Workbooks("QuestionnaireResponses.xlsm").Activate
'Put code to update links in here
ThisWorkbook.UpdateLink Name:="myfilepathgoeshere.QuestionnaireResponses.xlsm", Type:=xlExcelLinks
'End update links
Thanks for any help, this one's a head scratcher.
Great idea from #Kyle. For those who having trouble forcing cell references to update, TextToColumns works.
However TextToColumns draws an error if the source range is empty, so if there's any chance of that being the case use an if statement with no action attached to skip over those instances.
My successful code looks like this:
Dim i As Integer
For i = 1 To 1004
'Scans through row 2 from col A onwards
'If cell is empty, does nothing.
'If cell is not empty, performs TextToColumns where source range = target range.
If IsEmpty(Workbooks("QuestionnaireResponses.xlsm").Worksheets_
("response1").Cells(2, i)) Then 'Does nothing if the cell is empty.
Else
Workbooks("QuestionnaireResponses.xlsm").Worksheets("response1").Cells(2, i).Select
Selection.TextToColumns Cells(2, i) 'Performs TextToColumns
End If
Next
All of my data is on the same long row. To apply the above to an entire spreadsheet, just nest everything between, and including, For i = 1 and Next within another For loop with different letter replacing i.

VBA activating a cell with a cell reference

So I have a very simple line of code that should activate a cell on another sheet but in the same workbook but I can't figure out why it doesn't work:
Sheets("me").Range(Cells(rownum, colnum)).Activate
It give an "application or object defined" error. rownum and colnum are defined variables and when hovering them in debug mode they show integer values.
You need to activate the worksheet before you activate a cell on it.
Try this instead:
Public Sub test()
With Sheets("me")
.Activate
.Cells(rownum, colnum).Activate
End With
End Sub
From Excel 2003 help:
Activates a single cell, which must be inside the current selection. To select a range of cells, use the Select method.
By the way, do you REALLY need to activate or select that range ? In 90% of the code I see, those .Select are totally unnecessary !

Resources