Excel Userform pass variable to Range - excel

I have a worksheet which I have set to let the user open a userform if it contains the text "[View Data]". My thought was that I can send the current active cell row into a variable and then apply it when retrieving data. This works partially, I can get the active cell row, but I am unable to apply it within the Range. The error occurs in Read_Data:
Run-time error '9': Subscript out of range
I would appreciate some help in getting to a solution
This is what I have for Modules -> Module1:
Public activeCellNow As Integer
This is what I have in Microsoft Excel Objects -> Sheet1:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Target
If 1 = .Cells.Count Then
activeCellNow = ActiveCell.row
If .Value = "[View Data]" Then Details.Show
End If
End With
End Sub
This is what I have in Forms -> Details
Private Sub UserForm_Activate()
MsgBox (activeCellNow)
Call Read_Data
End Sub
The message box shows the correct row number
Private Sub Read_Data()
txt_manager.Value = Sheets("Sheet1").Range("B" & (activeCellNow)).Value
End Sub

Resolved issue. I tried it on a new project and the syntax I wrote worked fine. Thanks to #Skin and #FunThomas for the tips :)

Related

What issue am I having running the same macro twice in the same workbook?

I have a workbook for which I need to use goal seek to calculate a value I've named "Zeta". I got the code working on one sheet, but when I try to use the same code on another sheet, it doesn't work. I don't get it
The code that works is shown below:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim inputCells As Range
'List all input cells
Set inputCells = Range("Zeta, BiotTarget,Diameter,k,h, " & _
"BiotTarget, SetCell, ChangeCell")
If Not Application.Intersect(Range(Target.Address), inputCells) Is Nothing Then
'Run the Goalseek Macro
Range(Range("SetCell").Value).GoalSeek Goal:=Range(Range("ToCell").Value), ChangingCell:=Range(Range("ChangeCell").Value)
End If
End Sub
The code that does not work is copy pasted from the above code with slight alterations to get it to work.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim inputCells As Range
'List all input cells
Set inputCells1 = Range("Zeta1, BiotTarget1,Thickness,kone,hone, " & _
"BiotTarget1, SetCell1, ChangeCell1")
If Not Application.Intersect(Range(Target.Address), inputCells1) Is Nothing Then
'Run the Goalseek Macro
Range(Range("SetCell1").Value).GoalSeek Goal:=Range(Range("ToCell1").Value), ChangingCell:=Range(Range("ChangeCell1").Value)
End If
End Sub
When I try to run the Macro, it gives error shown in the photo. All the cells are the same idea, but I renamed them with a 1 at the end to show the difference. Also, Diameter is changed to thickness.
Can anyone help out here?

Clear range selected in Excel listbox and delete range name

Suppose I have a listbox in a userform module. When shown, it contains three range names. Let's call them Range1, Range2, and Range3. When the user clicks on one, I want the corresponding range to be cleared and the range name to be deleted.
Thanks to anyone who can advise me on the code to do this.
Sorry I can't comment.But I think this link will help you.
http://www.ozgrid.com/forum/showthread.php?t=83396
I actually deleted the range. Alternatively, you could use Range(.Value).ClearContents to clear only the data or Range(.Value).Clear to clear the data and formatting from the range.
Private Sub ListBox1_Click()
With ListBox1
If Not IsNull(.Value) Then
On Error Resume Next
Range(.Value).Delete
ThisWorkbook.Names(.Value).Delete
On Error GoTo 0
End If
End With
RefreshRangeList
End Sub
Sub RefreshRangeList()
Dim n As Name
ListBox1.Clear
For Each n In ThisWorkbook.Names
ListBox1.AddItem n.Name
Next
End Sub
Private Sub UserForm_Initialize()
RefreshRangeList
End Sub

Why can I not see a Named Range that is scoped as Workbook from any VBA code?

I have created a Named Range using the Name Manager. It is called Vol_Check. It is scoped as Workbook.
If it is scoped as workbook, why can I not see it in VBA code from other sheets or ThisWorkbook or Modules.
Even when I try to reference it directly, it will not work.
Here is a code example that I cannot make work.
Private Sub CommandButton1_Click()
If ThisWorkbook.Sheets("sheet1").Range("Vol_Check").Value <> 1 Then
MsgBox ("Some message ")
End If
End Sub
If you are using a Named Range "Vol_Check", then use the code below to read a value from one of the cells inside the Named Range.
In the example, let's say your Named Range includes Range B2:B2, then the code line Range("Vol_Check")(1, 1) refers to Cell B2
Private Sub CommandButton1_Click()
' just for debug - shows the first row and first column in the Named Range
MsgBox Range("Vol_Check")(1, 1)
If Range("Vol_Check")(1, 1) <> 1 Then
MsgBox ("Some message ")
End If
End Sub
Try using Worksheet.Evaluate instead:
Private Sub CommandButton1_Click()
If ThisWorkbook.Sheets(1).Evaluate("Vol_Check").Value <> 1 Then
MsgBox "Some message "
End If
End Sub
Problem solved.
It turns out that I was not defining the Named Range properly with the Name Manager tool. Even tho I was marking it 'Workbook' in scope, my other error was messing it up.
Thanks everyone.
Rich

VB - Excel checking previous value give an error

I am trying to learn a bit of VB and there is an exercise to change a value and check the previous value and if it is different do something. I eventually found a solution I could understand and get to work from : How do I get the old value of a changed cell in Excel VBA? - solution 4.
My code is:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Variant
For Each cell In Target
If previousRange.Exists(cell.Address) Then
If Not Application.Intersect(Target, Me.Range("B12:B12")) Is Nothing Then
If previousRange.Item(cell.Address) <> cell.FormulaR1C1 Then
cell.Interior.ColorIndex = 36
End If
End If
End If
Next
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cell As Variant
Set previousRange = Nothing 'not really needed but I like to kill off old references
Set previousRange = CreateObject("Scripting.Dictionary")
For Each cell In Target.Cells
previousRange.Add cell.Address, cell.FormulaR1C1
Next
End Sub
The next exercise was to add a button and perform an action depending on the user's response. So I added:
Private Sub CommandButton2_Click()
Dim currentValue, message As Integer
currentValue = Range("C3").Value
message = MsgBox("Click OK to add 1, cancel to leave", vbOKCancel, "Addition")
If message = 1 Then
Range("C3").Value = currentValue + 1
End If
End Sub
The problem I have is that the button adds one to C3 but then falls over at the If previousRange.Exists(cell.Address) statement on the Worksheet_Change sub.
All the code is defined on Sheet1, but I do not seem to have a previous value generated for my button value(C3). How do I generate the previous value, or what am I missing?
Regards
J
As I seemed to have made things worse I have created a new spreadsheet with just the change events code and nothing else to try and simplify the problem. So the complete code I have now is:
Option Explicit
Dim previousRange As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Variant
For Each cell In Target
If previousRange.Exists(cell.Address) Then
If Not Application.Intersect(Target, Me.Range("B12:B12")) Is Nothing Then
If previousRange.Item(cell.Address) <> cell.FormulaR1C1 Then
cell.Interior.ColorIndex = 36
End If
End If
End If
Next
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cell As Variant
Set previousRange = Nothing 'not really needed but I like to kill off old references
Set previousRange = CreateObject("Scripting.Dictionary")
For Each cell In Target.Cells
previousRange.Add cell.Address, cell.FormulaR1C1
Next
End Sub
Now if I change the B12 cell, the previousRange As New Dictionary code is highlighted, and a message states "Compile error:User defined type not defined".
This code used to work before I introduced the message box and made a subsequent change. Must be user error. Can you help?
Regards J.
The .Exists method is used on dictionary objects, like the example you've cited. But I don't see where you've declared a dictionary object in your code. Maybe you're missing a declaration statement for it?
Dim previousrange As New Dictionary
Please note that, like the solution you've cited, you'll need to declare this before the sub routine. Also, you'll need to enable the Microsoft Scripting Runtime. Here's how:
In the VBA editor, go to the Tools menu and click on References...
In the Available References list box, scroll down until you see Microsoft Scripting Runtime. Make sure its check box is checked.
Click OK.
Now you're able to use Dictionary objects.

How do I pass the contents of the "Target" range in a "Worksheet_SelectionChange event to a sub?

Sheet 1 of my workbook contains (besides other data) a list of the other worksheets in column A. I wish to be able to click on any cell in column A5:A50 and go to the appropriate worksheet listed in that cell. My Sheet1 code is:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Me.Range("A5:A50")) Is Nothing Then SelectWorksheet
End Sub
and Module2 is:
Sub SelectWorksheet()
Dim strName As String
strName = Sheet1.Range("Target").Text (Error occurrs here: "Method 'Range' of object 'Worksheet' failed")
Sheets(strName).Select
End Sub
How do I get this to work as I expect? I know I could just click on the appropriate worksheet tab but I'm trying to learn how to code in VBA. Thanks. By the way, how do I get my post to show the code as typed in the question box?
Like this. You probably want to use the _SelectionChange event instead of the _Change event. Or you may find it necessary to use both events to trigger it. In any case here is how you pass the variable to another subroutine/module:
Sub Worksheet_SelectionChange(byVal Target as Range)
'Some code...
'
Call OtherMacro(Target)
'
End Sub
And then in your other macro, declare a range variable as required argument, like so:
Sub SelectWorksheet(rng as Range)
'
Dim strName as String
' at this point you can work with the "rng" variable, because it's been received from the other subroutine
strName = rng.Value
Sheets(strName).Activate
'
End Sub
You would need to add additional test to make sure user has not selected multiple cells, etc., but this should get you started.
Why not pass the sheet name from the cell to the sub?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Me.Range("A5:A50")) Is Nothing _
And Target.Cells.Count = 1 Then SelectWorksheet (Target.Value)
End Sub
Sub SelectWorksheet(strName As String)
Sheets(strName).Select
End Sub
I've also done a check to make sure that only one cell is in the selection.

Resources