Replacing a value in a cell with another - vba

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

Related

Set Range as Found String Location in VBA

I'm trying to set a range in VBA as the range of the inputted string that I am looking for. The full procedure is supposed to pop up a dialog box to look for a specific string, find the string, create a range called location, set this range to the range of the string that was found, move a finite amount of columns to the right, and with that new columns value, print a string into that range.
The problem right now is that for some reason It is not setting the range to the range of the string it finds.
There is only one instance of the string throughout the workbook.
I'm also relatively new to VBA so there are something commands I don't know or understand how they work.
Sub test()
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim Inp As String
Dim Loc As Range
Dim Row As Integer
Dim Col As Integer
Dim NewLoc As Range
Dim Sh As Worksheet
Inp = InputBox("Scan ESD Tag")
For Each Sh In ThisWorkbook.Worksheets
With Sh.Columns("A")
Set Loc = .Find(What:=Inp)
End With
Next
Row = Loc.Row
Col = Loc.Column + (3 * 5)
Set NewLoc = Worksheets("Building 46").Cells(Row, Col)
NewLoc.Value = "Over Here"
Range("G2") = 6
End Sub
Your problem is probably that your final block should be inside the loop as otherwise Loc is likely to be Nothing (unless the term is found on the last sheet) and your code will error. You should also check first that it is found to avoid such errors.
Sub test()
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim Inp As String
Dim Loc As Range
Dim Row As Integer
Dim Col As Integer
Dim NewLoc As Range
Dim Sh As Worksheet
Inp = InputBox("Scan ESD Tag")
For Each Sh In ThisWorkbook.Worksheets
With Sh.Columns("A")
Set Loc = .Find(What:=Inp)
If Not Loc Is Nothing Then
Row = Loc.Row
Col = Loc.Column + (3 * 5)
Set NewLoc = Worksheets("Building 46").Cells(Row, Col)
NewLoc.Value = "Over Here"
Range("G2") = 6 'should specify a sheet here
Exit Sub
End If
End With
Next
End Sub

Access a hyperlinked cell from another cell in same sheet 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"

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

VBA: VLookup between two workbooks

I am wondering if someone can help me out. I created a Userform with 3 comboboxes. Combobox 1 and 2 list all open workbooks. Combobox 3 lists the worksheets from Combobox 2. I now want to run a Vlookup. The lookup values are the values (in this case product codes) in each cell beginning at D9 to the last cell with a value in Column D of the first Worksheet of Combobox2's. The lookup range will be ("A5:S###"[number of rows varies depending on the file]").
The Vlookup formula should be in the Column I of the first Worksheet of Combobox2's value starting at "I9" looping through each cell in I9 until all the Codes in D9 are looked up.
I keep getting error the major one being “Runtime-error '9'”: Subscript out of range. Here is my code.
Option Explicit
Private Sub CancelButton_Click()
Stopped = True
Unload Me
End Sub
Private Sub ComboBox1_Change()
Dim ScheduleA As Workbook
Dim Termset As Worksheet
Set ScheduleA = Workbooks(Me.ComboBox1.Value)
With Me.ComboBox3
For Each Termset In ScheduleA.Worksheets
.AddItem Termset.Name
Next Termset
End With
End Sub
Private Sub FillACDButton_Click()
Dim ACDRebateInfo As Worksheet
Dim lastRow As Long
Dim NewRebate As Single
Dim NewRebateType As String
Dim LookUp_Range As Range
Dim ActionCode As String
Dim ACD_NewRebate As Range
Dim ACD_NewRebateType As Range
Dim ACD_ActionCode As Range
Dim SCC As Range
Dim Cell As Range
Set ACDRebateInfo = Workbooks(Me.ComboBox2.Value).Worksheets(1)
Set ACD_NewRebate = ACDRebateInfo.Range("I9:I500")
Set ACD_NewRebateType = ACDRebateInfo.Range("J9:J500")
Set ACD_ActionCode = ACDRebateInfo.Range("B9:B500")
Set LookUp_Range = Worksheets(Me.ComboBox3.Value).Range("A5:S400")
Set SCC = ACDRebateInfo.Range("D9:D230")
With ACDRebateInfo
For Each Cell In ACD_ActionCode
ActionCode = Application.WorksheetFunction.VLookup(SCC, LookUp_Range, 17, False)
Next Cell
End With
Unload Me
End Sub
Private Sub UserForm_Initialize()
Dim wkb As Workbook
For Each wkb In Application.Workbooks
Me.ComboBox1.AddItem wkb.Name
Me.ComboBox2.AddItem wkb.Name
Next wkb
End Sub
Not sure this is your issue but this piece of code does not make sense:
For Each Cell In ACD_ActionCode
ActionCode = Application.WorksheetFunction.VLookup(SCC, LookUp_Range, 17, False)
Next Cell
You are looping through the Action Codes but not using the Cell variable