VBA activating a cell with a cell reference - excel

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 !

Related

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).

Can an Excel cell formula refer to a UserForm control?

I have a UserForm with text boxes that are already bound to certain worksheet cells through the ControlSource property. I need to run a calculation between two of these bound values and have the result end up in a third worksheet cell. I know there are numerous ways this can be done, but I'm wondering whether there's some way to do this as a formula in the worksheet cell that references the UserForm control values. For example, I would like to be able to put a formula in cell C3 that goes something like
= UserForm1.TextBox1.Value * UserForm1.TextBox2.Value
but I haven't found any reference that addresses using worksheet cell formulas to fetch values directly from UserForm controls. (And no, in this case I can't just reference the bound cells by plugging something like "= A1 * B2" into cell C3. This question is specifically about whether it's feasible to reference a UserForm control from within a worksheet cell formula.)
Thanks in advance for any helpful suggestions.
The only way to refer to the property of an ActiveX control on a worksheet, is via a user-defined-function, such as:
Public Function GetTextBoxValue(TextBoxName As String) As String
On Error GoTo 0
Dim o As OLEObject
Set o = Sheet1.OLEObjects(TextBoxName)
On Error Resume Next
If Not o Is Nothing Then
GetTextBoxValue = o.Object.Text
End If
End Function
Then call the function from a cell, like: =GetTextBoxValue("TextBox1")

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.

Get visible row and column number

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

Create A popup InputBox from a cell and right the value to the next one

Hello this is my first question here and I'm new in VBA programming. I'm looking for a VBA code that would allows me when I select a cell on a range of cells to pop-up an input box to put some values.
For example when I select a cell from column B an input box pops up, requiring a value that goes to next cell in column C. That's because in the column B I have stored a formula (& the cell is locked) and I would not like to be deleted or changed by the user although I need his Input Value to be calculated by the formula, so I choose to store this value in a hidden cell next to it and make the reference into my formula.
How is this possible with VBA?
Thanks in advance,
Harris
This technique uses double click rather than single click. Your protection must allow the user to double click cells in column B
Enter the following Event macro in the worksheet code area:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim t As Range, B As Range
Set t = Target
Set B = Range("B:B")
If Intersect(t, B) Is Nothing Then Exit Sub
Cancel = True
t.Offset(0, 1).Value = Application.InputBox(Prompt:="Enter data value", Type:=1)
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!
I would suggest using the following Code:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
If Not Intersect(Target, Range("B:B")) Is Nothing Then
Cells(Target.Row, Target.Column + 1).Value = Application.InputBox("Insert your value please")
End If
End If
End Sub
This pops an inputbox up if you select any cell in column B and puts the value to the Cell in C. You have to put the Code directly into the particular Sheet in the VBA Window.

Resources