Excel - How to double click a cell and reference another sheet? - excel

I’m wanting to know if this is possible, and how would I go about doing so:
I’d like to be able to double click a cell (in column Z), reference what is in Column G of that same row, and then find and set focus from the info found in column G on another sheet.
So when I double click the cell in Z1 for example, it looks for what information is in G1 and finds it on another sheet and sets focus to that new cell.
Is this possible?
Thanks

Yes, you need to implement Worksheet_BeforeDoubleClick event handler then you may do anything you like, handler is an event of Worksheet object. Do your main code in Module code to keep things reusable across multiple sheets.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Call Module1.onDrillDownToData(Target)
End Sub
- - -
Public Function onDrillDownToData(ByRef sender As Range)
Dim ws as worksheet
Dim iCol As Long
Dim iRow As Long
Dim dt As Date
set ws = sender.Parent
' do anything you want with worksheet
' sender is the origin cell
iCol = Sender.Column
iRow = Sender.Row
dt = Now()
ws.Cells(iRow, iCol).Value = "'" & Format(dt, "yyyy\-MM\-dd", vbMonday)
ws.Cells(iRow + 1, iCol).Value = "'" & Format(dt, "hh\:nn\:ss", vbMonday)
set ws = Application.Worksheets("TargetSheet")
ws.Activate
ws.Range("A5").Activate
End Function

Worksheet BeforeDoubleClick
Copy the following code into the sheet module of the sheet where you are going to double-click (In VBE in the project explorer double-click on the appropriate sheet to open its code window).
Before exiting VBE, adjust the constants, especially the destination worksheet name (wsName, the name in parentheses), in the code.
The Code
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
' Define constants.
Const wsName As String = "Sheet2" ' Destination Worksheet Name
Const SourceColumn As String = "Z" ' Source Column String
Const CriteriaColumn As String = "G"
' Not sure if this is even possible.
If Target.Rows.Count > 1 Then Exit Sub
If Not Intersect(Target, Columns(SourceColumn)) Is Nothing Then
Dim Criteria As Variant
Criteria = Cells(Target.Row, CriteriaColumn)
If Not IsError(Criteria) And Not IsEmpty(Criteria) Then
Dim cel As Range
With ThisWorkbook.Worksheets(wsName)
Set cel = .Cells _
.Find(What:=Criteria, _
After:=.Cells(.Rows.Count, .Columns.Count), _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
MatchCase:=False) ' Change to True is necessary
If Not cel Is Nothing Then
.Activate
cel.Select
End If
End With
End If
End If
End Sub

Related

Use the value of an active cell to hyperlink (or VBA) to the same value on another sheet in same workbook

I am a fairly advanced excel user, but limited experience in VBA coding; can anyone give me a hand, or start me in the right direction please?
I have two sheets with tables:
The first (MASTER) sheet has product information which includes a unique stock code (SKU); it also identifies the SKU of any product which can be used as a substitute for that first product as a separate column entry. Both the product details of the MASTER product and the potential SUBSTITUTE product are in this MASTER sheet table.
The second (SUBSTITUTE) sheet is filtered to show the products which have potential substitutes along with the SKU of that potential substitute. It gets this information from the MASTER sheet and table.
I want to be able to select the potential substitute SKU cell on the SUBSTITUTE sheet, and then either hyperlink or use VBA to use that value to jump to the cell in the MASTER sheet that has that same value as that in the SUBSTITUTE’s cell.
In summary the pseudo code is:
Go to SUBSTITUTE worksheet
Position/select on a SKU code in the table
THE CODING WOULD START HERE. (VBA OR HYPERLINK)
Get that cell’s value and store as a variable
JUMP to MASTER worksheet
Find the value of the variable in the SKU column (SKUs are unique)
Make that cell with the same valu as the variable the active cell
Is it do-able?
Thanks in advance
Terry, the macro below may take care of most of your needs. You can create a keyboard shortcut for this macro and each time you run the macro, it will search for the text in the (SUBSTITUTE-sheet) cell you selected, in the MASTER sheet in your excel file and will show it to you. After that you can manually change the data or you can edit macro according to your needs. See sample screenshots below.
Sub Macro4()
my_text = Selection.Value
Sheets("MASTER").Activate
Cells.Select
On Error GoTo my_err
Selection.Find(What:=my_text, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Exit Sub
my_err: MsgBox "search text not found"
Sheets("SUBSTITUTE").Select
End Sub
Activate Cell on Another Worksheet
Adjust the values in the constants section.
This runs automatically (on its own), there's nothing to run manually.
When you select a SKU cell in the Substitute worksheet, it activates the cell containing the same SKU value in the Master worksheet making it the top-most and left-most cell (modify if necessary).
Sheet Module e.g. Substitute
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
SelectSKU Target
End Sub
Standard Module e.g. Module1
Option Explicit
Sub SelectSKU(ByVal Target As Range)
' Source
Const shRow As Long = 1
Const sTitle As String = "SKU"
' Destination
Const dName As String = "Master"
Const dhRow As Long = 1
Const dTitle As String = "SKU"
' Source
If Target Is Nothing Then Exit Sub
Dim ws As Worksheet: Set ws = Target.Worksheet
If shRow < 1 Then Exit Sub ' Source Header Row too small
If shRow >= ws.Rows.Count Then Exit Sub ' Source Header Row too great
Dim shCell As Range: Set shCell = RefHeader(ws, sTitle, shRow)
If shCell Is Nothing Then Exit Sub ' Source Header not found
Dim scrg As Range: Set scrg = RefColumn(shCell.Offset(1))
If scrg Is Nothing Then Exit Sub ' Source Range is empty
Dim sCell As Range: Set sCell = Intersect(Target.Cells(1), scrg)
If sCell Is Nothing Then Exit Sub ' cell not in Source Range
If IsError(sCell) Then Exit Sub ' cell contains an error
If Len(sCell.Value) = 0 Then Exit Sub ' cell is blank i.e. no SKU value
Dim sValue As String: sValue = CStr(sCell.Value)
' Destination
If dhRow < 1 Then Exit Sub ' Destination Header Row too small
If dhRow >= ws.Rows.Count Then Exit Sub ' Destination Header Row too great
Dim dws As Worksheet: Set dws = RefWorksheet(ws.Parent, dName)
If dws Is Nothing Then Exit Sub ' Destination Worksheet not found
Dim dhCell As Range: Set dhCell = RefHeader(dws, dTitle, dhRow)
If dhCell Is Nothing Then Exit Sub ' Destination Header not found
Dim dcrg As Range: Set dcrg = RefColumn(dhCell.Offset(1))
If scrg Is Nothing Then Exit Sub ' Destination Range is empty
Dim dcell As Range: Set dcell = dcrg.Find(sValue, _
dcrg.Cells(dcrg.Cells.Count), xlFormulas, xlWhole)
If dcell Is Nothing Then Exit Sub ' SKU not found in Destination Range
dws.Activate
dcell.Activate
' Optional. Remove or modify one or both if you don't like it.
With ActiveWindow
.ScrollRow = dcell.Row
.ScrollColumn = dcell.Column
End With
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: In a row ('HeaderRow') of a worksheet ('ws'), creates
' a reference to the first cell whose value is equal
' to a string ('Title'). Case-insensitive.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefHeader( _
ByVal ws As Worksheet, _
ByVal Title As String, _
Optional ByVal HeaderRow As Long = 1) _
As Range
If ws Is Nothing Then Exit Function
If HeaderRow < 1 Then Exit Function
If HeaderRow > ws.Rows.Count Then Exit Function
With ws.Rows(HeaderRow)
Set RefHeader = .Find(Title, .Cells(.Cells.Count), xlFormulas, xlWhole)
End With
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to the one-column range from the first cell
' of a range ('rg') through the bottom-most non-empty cell.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumn( _
ByVal rg As Range) _
As Range
If rg Is Nothing Then Exit Function
With rg.Cells(1)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Function
Set RefColumn = .Resize(lCell.Row - .Row + 1)
End With
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: In a workbook ('wb'), creates a reference to the worksheet
' named after a string ('WorksheetName').
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefWorksheet( _
ByVal wb As Workbook, _
ByVal WorksheetName As String) _
As Worksheet
If wb Is Nothing Then Exit Function
On Error Resume Next
Set RefWorksheet = wb.Worksheets(WorksheetName)
On Error GoTo 0
End Function

Change color of cells if the value matches values of other worksheets values in a column

So here's the code. I have a calendar with dates in B4:H9. I want to change the color of the cells if the those dates are in a list (column, on different worksheet).
This might be a bit heavy to run if there are many different dates in the worksheet, but that doesn't matter.
What am I doing wrong here? It keeps giving me different error codes, when trying different things.
Sub check_Click()
Dim area As Range
Dim item1 As Range
Dim item2 As Range
Dim sheet As Worksheet
Dim columnlist As Range
sheet = Range("E2").Value
area = Range("B4:H9")
columnlist = Worksheets(sheet).Range("A2:A" & Rows.Count)
For Each item1 In area
For Each item2 In columnlist
If item1.Value = item2.Value Then
item1.Interior.ColorIndex = RGB(255, 255, 0)
End If
Next item2
Next item1
End Sub
As SuperSymmetry mentioned, when you define objects (e.g. ranges, sheets) you need to use the Set keyword. I will not get into that explanation. However few things that I would like to mention...
Try and give meaningful variable names so that you can understand what are they for.
Work with objects so that your code knows which sheet, which range are you referring to.
No need of 2nd loop. Use .Find to search for your data. It will be much faster
To set RGB, you need .Color and not .ColorIndex
Is this what you are trying? (Untested)
Option Explicit
Sub Check_Click()
Dim rngData As Range
Dim rngReference As Range
Dim aCell As Range
Dim matchedCell As Range
Dim ws As Worksheet
Dim lastRow As Long
Dim worksheetName As String
'~~> Change the sheet name accordingly
worksheetName = ThisWorkbook.Sheets("Sheet1").Range("E2").Value
Set ws = ThisWorkbook.Sheets(worksheetName)
With ws
'~~> Find the last row in Col A
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Set your range
Set rngData = .Range("B4:H9")
Set rngReference = .Range("A2:A" & lastRow)
'~~> Loop through your data and use .Find to check if the date is present
For Each aCell In rngData
Set matchedCell = rngReference.Find(What:=aCell.Value, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not matchedCell Is Nothing Then
'~~> Color the cell
matchedCell.Interior.Color = RGB(255, 255, 0)
End If
Next aCell
End With
End Sub
This should do the trick, I don't like leaving ranges without their sheet, but since I believe you are using a button, there should be no problem:
Option Explicit
Sub check_Click()
'We are going to use a dictionary, for it to work you need to:
'Go to Tools-References-Check the one called: Microsoft Scripting Runtime
Dim DatesToChange As Dictionary: Set DatesToChange = LoadDates
Dim area As Range: Set area = Range("B4:H9")
Dim item As Range
For Each item In area
If DatesToChange.Exists(item.Value) Then
item.Interior.Color = RGB(255, 255, 0)
End If
Next item
End Sub
Private Function LoadDates() As Dictionary
Set LoadDates = New Dictionary
Dim arr As Variant: arr = ThisWorkbook.Sheets(Range("E2")).Range("A:A")
Dim i As Long
For i = 2 To UBound(arr)
'This here will break the loop when finding an empty cell in column A
If arr(i, 1) = vbNullString Then Exit For
'This will add all your dates in a dictionary (avoiding duplicates)
If Not LoadDates.Exists(arr(i, 1)) Then LoadDates.Add arr(i, 1), 1
Next i
End Function
When you define objects (e.g. ranges, sheets) you need to use the Set keyword
Set area = Range("B4:H9")
Set columnlist = Worksheets(sheet).Range("A2:A" & Rows.Count)
Worksheets() accepts either an Integer or a String. Therefore, sheet should be of Type String
Dim sheet As String
You're also setting columnlist to the whole column in the sheet so you're looping hundreds of thousands more times unncessarily. Change it to
With Worksheets(sheet)
Set columnlist = .Range(.Range("A2"), .Range("A" & Rows.Count).Offset(xlUp))
End With
The above should fix the errors in your code and make it run a little faster. However, there's still big room for improvment in the efficiency of the code. For example, instead of changing the colour inside the loop, you should build a range and set the colour one time after the loop.
Also consider resetting the colour at the beginning of the code with
area.Interior.Pattern = xlNone
I would personally go with conditional formatting as #SiddharthRout suggested in the comments.
Edit following comment
Here's my rendition
Sub check_Click()
Dim dStart As Double
dStart = Timer
Dim rngCalendar As Range
Dim vCalendar As Variant
Dim shtDates As Worksheet
Dim vDates As Variant, v As Variant
Dim i As Long, j As Long
Dim rngToColour As Range
' Change the sheet name
With ThisWorkbook.Sheets("Calendar")
Set rngCalendar = .Range("B4:H9")
vCalendar = rngCalendar.Value
Set shtDates = ThisWorkbook.Sheets(.Range("E2").Value)
End With
With shtDates
vDates = .Range(.Range("A2"), .Range("A" & Rows.Count).End(xlUp)).Value
End With
For i = 1 To UBound(vCalendar, 1)
For j = 1 To UBound(vCalendar, 2)
For Each v In vDates
If v <> vbNullString And v = vCalendar(i, j) Then
If rngToColour Is Nothing Then
Set rngToColour = rngCalendar.Cells(i, j)
Else
Set rngToColour = Union(rngToColour, rngCalendar.Cells(i, j))
End If
Exit For
End If
Next v
Next j
Next i
rngCalendar.Interior.Pattern = xlNone
If Not rngToColour Is Nothing Then
rngToColour.Interior.Color = RGB(255, 255, 0)
End If
MsgBox "Time taken: " & Format(Timer - dStart, "0.0000s")
End Sub
With a list of 2500 dates it took 0.0742s on my machine.

How to create hyperlink to macro code to cut and paste?

I have an Excel sheet with 5 tabs, column A in each is where I want a clickable cell.
When that cell is clicked, I want it to cut the 4 cells to the right of it on the same row and paste it on the next tab.
Clicking A1 would cut B1, C1, D1, E1 and paste it on the next tab, on the next empty row.
Same with the next tab until that row has made it to the final tab.
All the data is on the first sheet, all the others are empty.
Once I click on the first sheet I want it to move to the next one, then when I click it on the next one I want it to move to the third one.
So far I have code that creates hyperlinks on the cells I highlight, but it displays (sheet name! cell number). I want to display a specific txt instead, like (complete) or (received). The display varies for each tab.
The code I have in the first sheet moves the cut row to the second sheet.
I tried pasting that code in the next sheet to move it to the third sheet but I get an error.
Code in module
Sub HyperActive()
Dim nm As String
nm = ActiveSheet.Name & "!"
For Each r In Selection
t = r.Text
addy = nm & r.Address(0, 0)
ActiveSheet.Hyperlinks.Add Anchor:=r, Address:="", SubAddress:= _
addy, TextToDisplay:=r.Text
Next r
End Sub
Code in sheet
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim r As Range
Set r = Range(Target.SubAddress)
r.Offset(0, 1).Resize(1, 4).Cut
Sheets("Wash Bay").Select
Worksheets("Wash Bay").Range("B" & Rows.Count).End(xlUp).Offset(1).Select
ActiveSheet.Paste
End Sub
I'd suggest using the Workbook_SheetFollowHyperlink event here. This is the workbook-level event, as opposed to the worksheet-level Worksheet_FollowHyperlink event.
From the docs:
Occurs when you choose any hyperlink in Microsoft Excel...
Parameters
Sh : The Worksheet object that contains the hyperlink
Target: The Hyperlink object that represents the destination of the hyperlink
Add the following code to the ThisWorkbook module (not the sheet code module).
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
If Sh.Index = Me.Worksheets.Count Then Exit Sub ' Do nothing if `Sh` is the last worksheet
Dim nextWs As Worksheet
Set nextWs = Me.Worksheets(Sh.Index + 1)
With nextWs
Dim lastRow As Long
lastRow = .Range("B" & .Rows.Count).End(xlUp).Row
End With
Dim rng As Range
Set rng = Sh.Range(Target.SubAddress)
rng.Offset(, 1).Resize(1, 4).Cut Destination:=nextWs.Range("B" & lastRow + 1)
Application.CutCopyMode = False
End Sub
IMPORTANT NOTE: In its current state, this assumes that the workbook only has worksheets (no chart sheets, for example).
EDIT: You can use this revised code if the workbook contains other sheet types besides worksheets:
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Dim indx As Long
indx = GetWorksheetIndex(Sh)
If indx = Me.Worksheets.Count Then Exit Sub
Dim rng As Range
Set rng = Sh.Range(Target.SubAddress)
Dim nextWs As Worksheet
Set nextWs = Me.Worksheets(indx + 1)
With nextWs
Dim lastRow As Long
lastRow = .Range("B" & .Rows.Count).End(xlUp).Row
End With
rng.Offset(, 1).Resize(1, 4).Cut Destination:=nextWs.Range("B" & lastRow + 1)
Application.CutCopyMode = False
End Sub
Private Function GetWorksheetIndex(ByVal ws As Worksheet) As Long
Dim w As Worksheet
For Each w In ws.Parent.Worksheets
Dim counter As Long
counter = counter + 1
If w.Name = ws.Name Then
GetWorksheetIndex = counter
Exit Function
End If
Next w
End Function
2nd EDIT:
I think you can rewrite HyperActive to something like this:
Sub HyperActive(ByVal rng As Range)
Dim ws As Worksheet
Set ws = rng.Parent
Dim fullAddress As String
fullAddress = "'" & ws.Name & "'!" & rng.Address
ws.Hyperlinks.Add Anchor:=rng, Address:="", SubAddress:=fullAddress, TextToDisplay:=rng.Text
End Sub
Then in the main Workbook_SheetFollowHyperlink code, add the following line:
HyperActive rng:=nextWs.Range("A" & lastRow + 1)

Find string in one worksheet and select it in another

I've got Workbook where I got names and hours worked of employees. I'm looking for comparing rows in one worksheet (Range B6:CC6) and find it in another with selection on cell with employee name (Range A1:A5000) when I change sheets from 1 to 2.
Tried some Range.Find and others, no idea how to do it
Public Sub FindPosition()
Dim Actcol As Integer, Pos As Range, Name As Range
Actcol = ActiveCell.Column
MsgBox "ActiveCell is" & Actcol
Set Pos = Cells(6, Actcol)
MsgBox Pos
Pos.Select
If Worksheets("Sheet2").Activate Then
Worksheets("Sheet2").Range("A1:AA5100").Select
Set Name = Selection.Find(Pos, LookIn:=xlValues)
End If
End Sub
First, if you want to trigger some macro by activation of Sheet2, you need to handle Activate event of Sheet2. This can be done by declaring subroutine in Sheet module like this.
Private Sub Worksheet_Activate()
'Codes you want to be run when Sheet2 is activated.
End Sub
Second, a simple way to find a cell with specific value is to use WorksheetFunction.Match. For example,
Dim SearchInRange As Range
Set SearchInRange = Range("A1:A5000")
Dim EmployeeName As Variant
EmployeeName = ... 'Actual employee name you want to search
On Error GoTo NotFound
Dim Index As Variant
Index = WorksheetFunction.Match(EmployeeName, SearchInRange, 0)
On Error GoTo 0
SearchInRange.Cells(Index).Select
GoTo Finally
NotFound:
' Handle error
Finally:
Range.Find may also work, but remember it has the side effect of changing the state of "Find and Replace" dialog box.
This may helps you
Option Explicit
Sub test()
Dim i As Long, LastRowA As Long, LastRowB As Long
Dim rngSearchValues As Range, rngSearchArea As Range
Dim ws1 As Worksheet, ws2 As Worksheet
'Set you worksheets
With ThisWorkbook
'Let say in this worksheet you have the names & hours
Set ws1 = .Worksheets("Sheet1")
'Let say in this worksheet you have the list of names
Set ws2 = .Worksheets("Sheet2")
End With
'Find the last row of the column B with the names from the sheet with names & hours
LastRowB = ws1.Cells(ws1.Rows.Count, "B").End(xlUp).Row
'Find the last row of the column A with the names from the sheet with list of names
LastRowA = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
'Set the range where you want to check if the name appears in
Set rngSearchArea = ws2.Range("A1:A" & LastRowA)
'Loop the all the names from the sheet with names and hours
For i = 6 To LastRowB
If ws1.Range("B" & i).Value <> "" Then
If Application.WorksheetFunction.CountIf(rngSearchArea, "=" & ws1.Range("B" & i).Value) > 0 Then
MsgBox "Value appears"
Exit For
End If
End If
Next i
End Sub
Oh right, I found solution. Thanks everyone for help.
Public Sub Position()
Dim Accol As Integer
Dim Pos As Range
Dim name As Range
ActiveSheet.name = "Sheet1"
Accol = ActiveCell.Column
Set Pos = Cells(6, Accol)
Worksheets("Sheet2").Activate
Worksheets("Sheet2").Range("a1:a5000").Select
Set name = Selection.Find(What:=Pos, After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
name.Select
End Sub
Last thing I would like to do which I cannot solve is where do I write automatically script running when I choose Sheet2?

Record active cell address in new sheet on button click

I want a button click to
record the address of the active cell I have selected in sheet 1, and place it into the next empty row in Column "B" on sheet 2.
On the button click as well, I wish for a MsgBox to display the corresponding row of Column "A", which contains reference numbers.
So far I have a working button, but my coding abilities are limited and this is all I have:
Private Sub CellReferenceBtn_Click()
MsgBox "The Active Cell Row and Column is " & ActiveCell(Row + 1, Column + 1).Address
End Sub
Any help is appreciated!
Here you go:
Private Sub CellReferenceBtn_Click()
With ActiveCell
Sheet2.[offset(b1,counta(b:b),)] = .Address
MsgBox Sheet1.Cells(.Row, 1)
End With
End Sub
It isn't clear on whether you require the worksheet name as well as the cell address. The worksheet name would make a full cell range address but if your intention is to use only the cell portion for something else then the worksheet name will just get in the way. Here are three possibilities.
'just the cell address without the worksheet name
Private Sub CommandButton1_Click()
With Worksheets("Sheet2")
.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = _
Selection(1).Address
'alternate for a larger selection of cells
'.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = _
Selection.Address
'pass focus back to the worksheet cells
Selection.Select
End With
End Sub
'cell range and the worksheet name
Private Sub CommandButton1_Click()
Dim addr As String
With Worksheets("Sheet2")
addr = Selection(1).Address(external:=True)
'alternate for a larger selection of cells
addr = Selection.Address(external:=True)
.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = Chr(39) & _
Replace(addr, _
Mid(addr, InStr(1, addr, Chr(91)), _
InStr(1, addr, Chr(93)) - InStr(1, addr, Chr(91)) + 1), _
vbNullString)
'pass focus back to the worksheet
Selection.Select
End With
End Sub
'full external path, worksheet name and cell range
'you can use this locally and it will abbreviate itself to what is necessary
Private Sub CommandButton1_Click()
With Worksheets("Sheet2")
.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = _
Selection(1).Address(external:=True)
'alternate for a larger selection of cells
.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = _
Selection.Address(external:=True)
Selection.Select
End With
End Sub
Something like
Sub AddForm()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Sheets(1)
Set ws2 = Sheets(2)
'check active sheet is sheet 1
If ActiveCell.Parent.Name = ws1.Name Then
ws2.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = ActiveCell.Address
MsgBox ActiveCell.Address
End If
End Sub

Resources