I'm quite new to VBA and I'm using it to automate a few simple tasks within my job. A small element of this is finding an integer which is always within a set of parentheses in cells from Column B, but the information before the parentheses changes regularly.
I need to get the values of column C to match the number from the parentheses in B. Currently, my code finds this value from the active cell's parentheses, and applies it to the whole column. I think my problem is in the declaration of the variables, but I'm hoping a more seasoned coder can help. Thanks!
Sub fillLeads()
'
' fillLeads Macro
Last = Cells(Rows.Count, "B").End(xlUp).Row
cellValue = Range("B2").Value
openingParen = InStr(cellValue, "(")
closingParen = InStr(cellValue, ")")
enclosedValue = Mid(cellValue, openingParen + 1, closingParen - openingParen - 1)
For i = Last To 2 Step -1
Cells(i, "C").Value = enclosedValue
Next i
End Sub
Please try:
Option Explicit
Sub fillLeads()
Dim Lastrow As Long, i As Long, StartPoint As Long, FinishPoint As Long
Dim SearchValue As String, FinalValue As String
With ThisWorkbook.Worksheets("Sheet1")
Lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
For i = 2 To Lastrow
SearchValue = .Range("B" & i).Value
StartPoint = InStr(1, SearchValue, "(") + 1
FinishPoint = InStr(1, SearchValue, ")") - StartPoint
FinalValue = Mid(SearchValue, StartPoint, FinishPoint)
.Cells(i, "C").Value = FinalValue
Next i
End With
End Sub
Results:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.