Access a hyperlinked cell from another cell in same sheet vba - vba

Following is a set up of my worksheet:
Cell M7 is hyperlinked to the large merged cell E6. My code needs to access the address of the destination cell from M7 (which will be E6) and assign that address to a range variable called "testing".
Once I have the address of the hyperlinked destination cell (E6) using "testing", I can then format the range address of "testing" however i want.
Here is what I have tried so far
Dim lcell As Range
Dim testing As Range
testing = lcell.Hyperlinks(1).Range
testing.Value = "TEST"
This gives me the following error:
Run-time error: 91
Object variable or With block variable not set

This function will return a reference to a hyperlink's target range whether it is the hyperlink is set by the HYPERLINK WorkSheetFunction or in the cell's hyperlink collection.
Sub Example()
Dim lcell As Range
Dim TestRange As Range
Set lcell = Range("A1")
Set TestRange = getHyperLinkTarget(lcell)
If Not TestRange Is Nothing Then
TestRange.Value = "TEST"
End If
End Sub
Function getHyperLinkTarget(HSource As Range) As Range
Dim address As String, formula As String
formula = HSource.formula
If HSource.Hyperlinks.Count > 0 Then
address = HSource.Hyperlinks(1).SubAddress
ElseIf InStr(formula, "=HYPERLINK(") Then
address = Mid(formula, InStr(formula, "(") + 1, InStr(formula, ",") - InStr(formula, "(") - 1)
End If
On Error Resume Next
If Len(address) Then Set getHyperLinkTarget = Range(address)
On Error GoTo 0
End Function
Thanks to ThunderFrame for pointing out the HYPERLINK Worksheet function.

This should do what you're after. You need to parse the contents of the M7 formula, so my code assumes the M7 formula only contains a Hyperlink formula like:
=HYPERLINK(E6,"RSDS")
And the VBA looks like:
Sub foo()
Const hyperlinkSignature = "=HYPERLINK("
Dim rng As Range
Set rng = Range("M7")
Dim hyperlinkFormula As String
hyperlinkFormula = Range("M7").formula
Dim testing As Range
'Check the cell contains a hyperlink formula
If StrComp(hyperlinkSignature, Left(hyperlinkFormula, Len(hyperlinkSignature)), vbTextCompare) = 0 Then
Dim hyperlinkTarget As String
hyperlinkTarget = Mid(Split(hyperlinkFormula, ",")(0), Len(hyperlinkSignature) + 1)
Set testing = Range(hyperlinkTarget)
testing.Value = "TEST"
Else
'Check if the cell is a hyperlinked cell
If Range("M7").Hyperlinks.Count = 1 Then
'Credit to Thomas for this line
Set testing = Range(Range("M7").Hyperlinks(1).SubAddress)
testing.Value = "TEST"
End If
End If
End Sub
Or, if you want a briefer method that doesn't bother checking the M7 formula contains a hyperlink, you could use:
Dim target As Range
Set target = Range(Range("M7").DirectPrecedents.Address)
target.Value = "Test"

Related

How can I copy a range of cells based on a Header to paste to another worksheet and match the headers?

I need a code to copy a range of cells (H21:H38) from my source worksheet (Acct Total) to a corresponding column on my target worksheet (COS% Tracking) based on matching headers. But the hiccup I have is that the header is in cell A6 on my source worksheet (Acct Total). I've researched it a bit and I've found this code that worked for someone else:
Sub CopyHeaders()
Dim header As Range, headers As Range
Set headers = Worksheets("ws1").Range("A1:Z1")
For Each header In headers
If GetHeaderColumn(header.Value) > 0 Then
Range(header.Offset(1, 0), header.End(xlDown)).Copy Destination:=Worksheets("ws2").Cells(2, GetHeaderColumn(header.Value))
End If
Next
End Sub
Function GetHeaderColumn(header As String) As Integer
Dim headers As Range
Set headers = Worksheets("ws2").Range("A1:Z1")
GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function
So my issue is that I don't know where to begin to edit this code to work like I need. This code worked by using the header above the range of cells but that won't do in my case. I'll attach pictures so that hopefully I'm not too vague.
Can someone help me to edit this code according to my needs?
Edit: Additional Picture for the source of the dates.
GL Code Tab
Look at the following construct as a starting point for a different way to solve the same problem. There are descriptive variables so you have an idea of what is happening.
Edit: As the target sheet row 3 is locked, code has been amended to use Match function to return column number where string is found (if found).
Essentially:
Set your source and target worksheets.
Set sourceWorksheet = wb.Sheets("Acct Total")
Set targetWorksheet = wb.Sheets("COS% Tracking")
Define your target value (the date you are trying to match on) and source range
targetDate = Trim$(sourceWorksheet.Range("A6"))
Set sourceRange = sourceWorksheet.Range("H21:H38")
Find the column number of where value (targetDate) is present in the target sheet
colNum = Application.WorksheetFunction.Match(targetDate, searchRange, 0)
Add error handling in case it is not present i.e. if date (as string) is not found....
ErrHand: 'code in this section.....
Set the address of where the target data will be pasted
Set targetRange = .Range(Cells(4, colNum), Cells(21, colNum))
Set the target range to be equal to the source range.
targetRange.Value = sourceRange.Value
Adapt as appropriate.
Putting it together you getting something along the lines of the following:
Option Explicit
Public Sub copydata()
Dim sourceRange As Range
Dim targetDate As String
Dim targetRange As Range
Dim wb As Workbook
Dim sourceWorksheet As Worksheet
Dim targetWorksheet As Worksheet
Dim searchRange As Range
Set wb = ThisWorkbook
Set sourceWorksheet = wb.Sheets("Acct Total")
Set targetWorksheet = wb.Sheets("COS% Tracking")
targetDate = Trim$(sourceWorksheet.Range("A6"))
Set sourceRange = sourceWorksheet.Range("H21:H38")
Set searchRange = targetWorksheet.Rows(3)
On Error GoTo ErrHand
Dim colNum As Long
colNum = Application.WorksheetFunction.Match(targetDate, searchRange, 0)
With targetWorksheet
Set targetRange = .Range(Cells(4, colNum), Cells(21, colNum))
targetRange.Value = sourceRange.Value
End With
ErrHand:
If Err = 1004 Then
MsgBox "Not found: " & targetDate
Err.Clear
Exit Sub
End If
End Sub
See the following:
Finding address of text in worksheet
Moving data between sheets

Replacing a value in a cell with another

I am writing a macro in Excel spreadsheets to replace a value in one cell by the content of another cell and loop through the original text replacing the same value, whenever it sees this word.
For example, I have a text in a range of cells, where every line has a word "tagname" I want to replace "tagname" with the value of cell A1 of the same spreadsheet, for example to say "Maggie" instead of tagname.
This is my code thus far:
Private Sub CommandButton21_Click()
Dim OriginalText As Range
Dim CorrectedText As Range
'definition of ranges
Set OriginalText = Range("H4:H10")
'setting of ranges
For Each OriginalText In CorrectedText
CorrectedText.Value = Replace(OriginalText.Value, "tagname", Range("D2").Value)
Next OriginalText
'a loop through the original text to replace the word "tagname" with the value of cell D4
Columns(2).Clear 'clear column 2 for the Corrected Text
Range("A24:A30").Offset(, 1).Value = CorrectedText
'copy corrected text in these cells
End Sub
I get runtime error 424, object required.
Just to put all of it together, this is how I would do it.
Sub CommandButton21_Click()
Dim correctedText As Range
Dim OriginalText As Range
Dim i As Long
Dim cel As Range
Set correctedText = Range("B24")
Set OriginalText = Range("H4:H10")
OriginalText.Replace "tagname", Range("d4")
correctedText.Resize(OriginalText.Rows.Count).Value = OriginalText.Value
OriginalText.Replace Range("d4"), "tagname"
End Sub
Or if you really want the loop:
Sub CommandButton21_Click()
Dim correctedText As Range
Dim OriginalText As Range
Dim i As Long
Dim cel As Range
Set correctedText = Range("B24")
Set OriginalText = Range("H4:H10")
i = 0
For Each cel In OriginalText
correctedText.Offset(i).Value = Replace(cel.Value, "tagname", Range("d4"))
i = i + 1
Next cel
End Sub

Changing value of TextBox due to selection of ComboBox VBA Excel

I have a project in which I have to change to value of a textbox to a value that is searched in a workseet against a vlaue that has been selected from a combobox. for example if I select "A" from the combobox the it should search the worksheet "test" find the input for A and change the text box value to 1 as this is the value entered for A. I have looked at some of the other questions that have been asked here but could not seem to get it to work for me. Below is the code that I have been trying to use.
Private Sub IDComboBox_Change()
Dim domainRange As Range
Dim listRange As Range
Dim selectedString As Variant
Dim lastRow As Long
If IDComboBox.ListIndex <> -1 Then
selectedString = IDComboBox.Value
lastRow = Worksheets("test").Range("A" & Rows.Count).End(xlUp).Row
Set listRange = Worksheets("test").Range("A2:A" & lastRow)
For Each domainRange In listRange
If domainRange.Value = selectedString Then
DomainOwnerTestBox.Value = "test"
End If
Next domainRange
End If
End Sub
Any help would be great. If you need anymore information then please let me know and also please be paient with me as im new to VBA.
Thanks
Try this code. It uses Excel built-in MATCH function to search for value in column A of worksheet 'test'.
Private Sub IDComboBox_Change()
Dim wks As Excel.Worksheet
Dim selectedString As Variant
Dim row As Long
Dim value As Variant
Set wks = Worksheets("test")
If IDComboBox.ListIndex <> -1 Then
selectedString = IDComboBox.value
On Error Resume Next
row = Application.WorksheetFunction.Match(selectedString, wks.Columns(1), 0)
On Error GoTo 0
If row Then
value = wks.Cells(row, 2) '<--- assuming that input values are in column 2.
DomainOwnerTestBox.value = value
Else
'Value not found in the worksheet 'test'
End If
End If
End Sub

.find works for me in one procedure but not another

Hello I have the code below. Essentially, it grabs unique values of a certain range in each worksheet and adds it to a range on the side of the same worksheet.
The .find method is not working for me like it does in another procedure and I would like an explanation why or what I am doing wrong or the difference between the behavior of the code when written differently. make sense?
sub methodtwo()
Dim cell As Range
Dim strDATE As String
Dim datehr As Range
For i = 1 To Sheets.Count - 4
Sheets(i).Activate
Set datehr = Sheets(i).Range("H2", Sheets(i).Range("H2").End(xlDown))
For Each cell In datehr
strDATE = cell.Value
Set cell = Sheets(i).Range("L1:L400").Find(What:=strName)
If cell Is Nothing Then
Sheets(i).Range("L1").End(xlDown).Offset(1, 0).Value = cell
End If
Next cell
Next i
End Sub
below is the code I have written before and a reference for writing the code above. In the code below, the find method works perfectly and adds unique values to the designated range...the code above does not.
Sub methodone()
Dim sh As Worksheet
Dim r As Long
Dim a As Range
Dim al As Range
Dim strName As String
For Each sh In Worksheets
sh.Activate
sh.Range("K1").Activate
Set al = ActiveSheet.Range("A2:A13000")
For Each a In al
strName = a.Value
Set Cell = ActiveSheet.Range("K1:K400").Find(What:=strName)
If Cell Is Nothing Then
ActiveSheet.Range("K1").End(xlDown).Offset(1, 0).Value = a
End If
Next a
Next sh
End Sub
I wanted the methodtwo() to do the exact same thing as methodone() except on the last 4 sheets.
Is the problem obvious? I'm working on my attention to detail..especially when using a previously written code for reference.
for methodone() I just had to change strNAME to strDATE which is a detail error when converting one procedure to the other. I also changed the "cell" after the IF statement to "strDATE"
sub methodtwo()
Dim cell As Range
Dim strDATE As String
Dim datehr As Range
For i = 1 To Sheets.Count - 4
Sheets(i).Activate
Set datehr = Sheets(i).Range("H2", Sheets(i).Range("H2").End(xlDown))
For Each cell In datehr
strDATE = cell.Value
Set cell = Sheets(i).Range("L1:L400").Find(What:=strDATE)
If cell Is Nothing Then
Sheets(i).Range("L1").End(xlDown).Offset(1, 0).Value = strDATE
End If
Next cell
Next i
end sub

Splitting data from barcode into different cells in MS Excel

I have a barcode scanner USB plug&play which is giving a string of data in one cell of Excel in this form 4449520450061198001
I want to split this data automatically in different cells everytime my scanner reads the code.
Please help.
Regards,
UPDATED
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const ws_range = "A1:A10"
Dim wb As Workbook
Dim ws As Worksheet
Dim i As Integer, k As Integer
Dim codestr As String
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
codestr = Target.Text
If Target <> "" Then
If Not Intersect(Target, Me.Range(ws_range)) Is Nothing Then
With Target
k = Len(codestr)
i = 2
Do Until i = k + 2
ws.Cells(Target.Row, i).Value = Mid(codestr, i - 1, 1)
i = i + 1
Loop
End With
End If
End If
End Sub
I haven't fully tested this but now after a value is inserted into column a it will be split into the cells to the right. Obviously modify A1:A10 to match what you need.