How to parse part of a cell containing x.x.x. and copy the data to another cell? - excel

I have an excel file I want to parse the beginning of each cell in column D and copy and paste the numbers in cell(same row,column B) How do I parse the cells with numbers 0 through 9 and "." and copy just that value x.x.x.x to column B? There is no standard format of how many numbers and periods at the start of the cell in column D. It could be 1.3.4 or 1.3.4. or 1.3 ect...
=====================================================================
'DIMENSIONING VARS AND PATHS
Dim Level As Range
Dim i, j, q(1 To 50) As Long
Dim numofchar As Long
Dim filepath As String
Dim filename As String
Dim PN As String
Dim HEADERrowcallout As Long
Dim LASTREQrowcallout As Long
Dim REQTEXTcolumncallout As String
Dim x As Long
Dim s As String
Dim count As Long
Dim Reqtext As Variant
Dim SectionText As Variant
'
'scanf(Input the correct row and column numbers). Used for determining start and endpoints of filtering files
HEADERrowcallout = InputBox("What row number are your headers in?")
LASTREQrowcallout = InputBox("What row number are your headers in?")
REQTEXTcolumncallout = InputBox("What is the column letter where ReqText is located? (A=1,B=2,D=4,ect...)")
'REQTYPEcolumncallout = InputBox("What is the column number from the left where the outline level is located? (A=1, B=2, ect...)")
'SECTIONcolumncallout = InputBox("What is the column number from the left where the outline level is located? (A=1, B=2, ect...)")
'
'stop screen updating
Application.ScreenUpdating = False
'
'show gridlines
ActiveWindow.DisplayGridlines = True
'
'Requirement Text to Section Maker --- Part (1)
'Part 1 filter string for the section number. (Numbers 1-10 & . until letters or space)
'Generate a string using the numbers and letters, ex [1.1.3.], cut & copy data to section column same row
For i = HEADERrowcallout + 1 To LASTREQrowcallout
'Get length of active cell. This is max that copied cell will be
LengthCell = Len(Cells(HEADERrowcallout + 1, REQTEXTcolumncallout))
SectionText = (LengthActiveCell)
Reqtext = (LengthActiveCell)
'while count != length, scan each array position from 0 until array position value != 1-10 or .
While x < LengthActiveCell
Select Case Cells()
Case "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."
Dim count As Long
x = x + 1
'If no more letters or .s, move to next cell
x = LengthCell
'if SectionText() = SectionText(0)
'Keep going down ReqText column until specified end
HEADERrowcallout = HEADERrowcallout + 1
End Sub
===========================
Picture of Excel Sheet

Edit: Now with comments explaining what the code does
Obviously you don't need the comments in your live version.
Paste the code below into a new Module, and then use it as a WorksheetFunction
(I took a guess as to what the function should be called). In any cell, enter =ExtractOutline(<cell address>), where <cell address> is the cell from which you wish to extract the x.x.x. bit.
Function ExtractOutline(strInput As String)
'Function iterates through the input string until we get to a
'character which isn't one in "0123456789." Each character which is
'one of these is added to the output as we go along
Dim strOut As String 'The output we're building
Dim intPos As Integer 'The position we've reached in the input
Dim str1Char As String 'The character found at the current position
intPos = 1 'We'll start at the first character
str1Char = Mid(strInput, intPos, 1) 'Extract the intPos-th character, in this case, the 1st.
While intPos <= Len(strInput) And WorksheetFunction.Find(str1Char, "0123456789." & str1Char) < 12
'While
'intPos <= Len(strInput)
'This makes sure we haven't iterated beyond the end of the input
'AND
'WorksheetFunction.Find(str1Char, "0123456789." & str1Char) < 12
'Looks for the current character in "0123456789."
'If it wasn't found we'd get an error (as output to the function)
'To prevent that add current character to end of "0123456789."
'Since "Find" returns the position, within the string,
'and "01234567890." as 11 characters, we only match the right bit if it
'is found before the 12th character
'Add the character to the output
strOut = strOut & Mid(strInput, intPos, 1)
'Increment ready for next time round the loop
intPos = intPos + 1
'Get the next character to be checked
str1Char = Mid(strInput, intPos, 1)
Wend
ExtractOutline = strOut
End Function

Or you can incorporate the following approach into your code...
Sub Alex()
Dim lr As Long
Dim rng As Range, cell As Range
Dim RE As Object
Dim Match As Object
lr = Cells(Rows.Count, 4).End(xlUp).Row
Set rng = Range("D2:D" & lr)
Set RE = CreateObject("VBScript.RegExp")
RE.Pattern = "([0-9]\.){1,}"
For Each cell In rng
If RE.test(cell.Value) = True Then
Set Match = RE.Execute(cell.Value)
cell.Offset(0, -2).Value = Left(Match(0), Len(Match(0)) - 1)
End If
Next cell
End Sub

Something like this
You can see RegExp sample here
code
Sub EddieBetts()
Dim rng1 As Range
Dim lngCnt As Long
Dim objRegex As Object
Dim X
Set rng1 = Range([d2], Cells(Rows.Count, "D").End(xlUp))
X = rng1.Value2
Set objRegex = CreateObject("VBScript.RegExp")
objRegex.Pattern = "([0-9\.])+"
For lngCnt = 1 To UBound(X, 1)
If objRegex.test(X(lngCnt, 1)) Then X(lngCnt, 1) = objRegex.Execute(X(lngCnt, 1))(0)
Next
rng1.Offset(0, -2).Value2 = X
End Sub

Related

Extract superscript and paste it into new column same row

I have been searching for a while now a code to help me to extract superscript characters (number 1 and 2) that are either in the middle or at the end of a string in column A. I need to cut them from the string and paste them into the same row, but on column C as a normal number.
I did not find any suitable solutions I could evev try. So I do not have any code because I do not know where to start. My data will have always less than 500 lines and has the same structure, but lines with superscript change.
Does anyone know to solve this problem please? Thanks a lot.
I would really appreciate the help.
Desired output: for every row where there is a superscript, cut it from string in Column A and paste it in column C as a normal number..
Sub extractSuperscript()
Dim rng As Range
Dim cell As Range
Dim i As Long
Dim j As Long
Dim result As String
' Define the range to process
Set rng = Range("A1:A10")
' Loop through each cell in the range
For i = 1 To rng.Cells.Count
Set cell = rng.Cells(i)
result = ""
' Loop through each character in the cell
For j = 1 To Len(cell.Value)
' Check if the character is a superscript 1 or 2
If Mid(cell.Value, j, 1) = "¹" Or Mid(cell.Value, j, 1) = "²" Then
' If the character is a superscript 1, add a 1 to the result string
If Mid(cell.Value, j, 1) = "¹" Then
result = result & "1"
' If the character is a superscript 2, add a 2 to the result string
ElseIf Mid(cell.Value, j, 1) = "²" Then
result = result & "2"
End If
End If
Next j
' Paste the result string into column C and remove the superscript from column A
cell.Offset(0, 2).Value = result
cell.Value = Replace(cell.Value, "¹", "")
cell.Value = Replace(cell.Value, "²", "")
Next i
End Sub
Let me know if this works
Let me know if the following works:
Option Explicit
Sub Superscript()
Application.ScreenUpdating = True
Dim wb As Workbook
Dim ws As Worksheet
Dim rngSuperscript As Range, c As Range
Dim iCount As Integer
Dim MyString As String
Set wb = ThisWorkbook
'Set it to sheet name where your data is
Set ws = wb.Sheets("Test")
'Change it to reflect your data
Set rngSuperscript = ws.Range("A2:A11")
For Each c In rngSuperscript
'temp text variable
MyString = c.Value
'loop through the string value
For iCount = 1 To Len(MyString)
'check if it is numeric
If IsNumeric(Mid(MyString, iCount, 1)) Then
'combine with the C column value (if any)
c.Offset(0, 2).Value = CLng(c.Offset(0, 2).Value & Mid(MyString, iCount, 1))
End If
Next
Next c
Application.ScreenUpdating = False
End Sub

I just tried to do multiple filtering using the below code. but am able to get the row number only at the first and after that am unable

Sub SplitWords()
Dim TextStrng As String
Dim Result() As String
Sheets("CO REPORT").Select
TextStrng = Range("K6").Value
Result() = Split(TextStrng)
For i = LBound(Result()) To UBound(Result())
Sheets("RSVP SCOPE").Select
'ActiveSheet.ShowAllData
ActiveSheet.Range("$A$1:$G$791").AutoFilter Field:=1, Criteria1:="=*" &
Result(i) & "*", Operator:=xlOr
MsgBox Result(i)
Worksheets("RSVP SCOPE").Range("1:1").EntireRow.Hidden = True
Set Report = Excel.ActiveSheet
Dim visRng As Range
Set visRng = Report.UsedRange.SpecialCells(xlCellTypeVisible)
Dim r As Range
Dim j As Integer
For Each r In visRng.Rows
j = r.row
MsgBox (j)
Worksheets("RSVP SCOPE").Range("1:1").EntireRow.Hidden = False
ActiveSheet.Range("$A$1:$G$791").AutoFilter.ShowAllData
Next
Next i
End Sub
For the above code, the split words is being used since there will be multiple words in a single cell. I need to copy a text from sheet1 and search that value in column 1 of sheet2 . Now after filtering I need to display the row number for every selected words. In the above code, the first iteration gets executed successfully. But for the second iteration I get a
Your question is broken. I see trouble:
...
' Dim r As Range
Dim r As Variant
...

Macro to remove duplicate values from an excel cell

I have duplicate email ids in an excel cell. (Each cell has around 5 to 6 emails which are repeated as below). Is there a macro to remove unique ones from the cell ? I have given an example below for reference, appreciate your assistance.
Cell 1
abc#cc.com
cde#bb.com
abc#cc.com
lmn#nn.com
cde#bb.com
Cell 2
jjj#cc.com
kk#dd.com
jjj#cc.com
Thanks
Auro
I used your data in a blank worksheet in Column A, and the output gets put in Column B.
You can change the loops and cell references to suit your needs.
I've also assumed you want the email addresses that were contained in a cell to remain grouped (once the duplicates have been removed) in the output.
This code also assumes the email addresses are separated by a 'carriage return'
Sub removeDuplicate()
'references: http://stackoverflow.com/questions/3017852/vba-get-unique-values-from-array
Dim wks As Worksheet
Dim rng As Range
Dim wordCount As Integer
Dim d As Object
Dim i As Integer
Dim j As Integer
Dim v As Variant
Dim outText As String
Set wks = Worksheets("Sheet1") '<- change sheet to suit needs
For j = 1 To 2 '<- change loop to suit needs
Set rng = wks.Range(Cells(j, 1), Cells(j, 1)) '<- change cell reference as required
Set d = CreateObject("Scripting.Dictionary")
'use carriage return (chr(10)) as the 'find' text
'Count Words/email addresses
wordCount = Len(rng) - Len(Replace(rng, Chr(10), "")) + 1
'split words by carriage return
arrWords = Split(rng, Chr(10))
For i = 0 To wordCount - 1
d(arrWords(i)) = 1
Next i
'create output text by re-grouping the split text.
outText = ""
For Each v In d.keys
If outText = "" Then
outText = v
Else
outText = outText & Chr(10) + v
End If
Next v
'output to adjacent cell
rng.Offset(0, 1).Value = outText
Set d = Nothing
Next j
Set wks = Nothing
End Sub

Excel copy cell values X times with increasing numbers in the end

I have a similar task as in there:
Copy value N times in Excel
But mine is a bit more complex.
So, I have this kind of sheet:
A B
dog-1.txt 3
cat-1.txt 2
rat-1.txt 4
cow-1.txt 1
The final result needs to be the following:
A
dog-1.txt
dog-2.txt
dog-3.txt
cat-1.txt
cat-2.txt
rat-1.txt
rat-2.txt
rat-3.txt
rat-4.txt
cow-1.txt
As you see it doesn't only multiply the cell content X times taken from column B, but it also increases the number in file name the same number of times with 1 step increase.
How could I achieve that?
Try the following (tried and tested):
Sub Extend()
Dim Rng As Range, Cell As Range
Dim WS As Worksheet, NewCell As Range
Dim Dict As Object, NewStr As String
Set WS = ThisWorkbook.Sheets("Sheet1") 'Modify as necessary.
Set Rng = WS.Range("A1:A5") 'Modify as necessary.
Set Dict = CreateObject("Scripting.Dictionary")
For Each Cell In Rng
If Not Dict.Exists(Cell.Value) Then
Dict.Add Cell.Value, Cell.Offset(0, 1).Value
End If
Next Cell
Set NewCell = WS.Range("C1") 'Modify as necessary.
For Each Key In Dict
For Iter = 1 To CLng(Dict(Key))
NewStr = "-" & Iter & ".txt"
NewStr = Mid(Key, 1, InStrRev(Key, "-") - 1) & NewStr
NewCell.Value = NewStr
Set NewCell = NewCell.Offset(1, 0)
Next Iter
Next Key
End Sub
Screenshot (after running):
The logic here is to get each name from the first column, store it as a dictionary key, then get the value beside it and store that that as the key-value. We then iterate inside each of the dictionary's keys, where we use the key-value as the upperbound of the iteration. During each iteration, we modify the string to change its number to the "current digit" of the iteration.
We choose C1 as the initial target cell. Every iteration, we offset it one (1) row below to accommodate the new/next iteration.
Let us know if this helps.
Tested , is this what u wanted :) ? (Working fine in my system)
Sub teststs()
Dim erange As Range
Dim lrow As Integer
Dim cnt As Integer
Dim rnt As Integer
Dim str As String
Dim lrow2 As Integer
With ActiveSheet
lrow = .Range("A" & Rows.Count).End(xlUp).Row ' finding the last row
For Each erange In .Range("A1:A" & lrow) ' loop though each each cell in the A column
cnt = erange.Offset(0, 1).Value
rnt = Mid(erange.Value, InStr(erange.Value, "-") + 1, 1)
For i = 1 To cnt 'Looping to cnt times
With Sheets("Sheet2")
lrow2 = .Range("A" & Rows.Count).End(xlUp).Row + 1
str = Replace(erange.Value, rnt, i, InStr(erange.Value, "-") + 1)
.Range("A" & lrow2).Value = Left(erange.Value, InStr(erange.Value, "-")) & str
End With
Next i
Next erange
End With
End Sub

Range of cells into single cell with carriage return

I am working through my first VBA book and would appreciate if someone would point me in the right direction. How would I transfer a range of rows into a single cell with carriage returns? I would then like to repeat this action for all ranges in the column.
I think I need to:
find the first cell with a value in the column
verify that the next row is not empty
find the last cell in the range
perform "the operation" on the range
Following up on my comments. here is a very simple way to achieve what you want.
Option Explicit
'~~> You can use any delimiter that you want
Const Delim = vbNewLine
Sub Sample()
Dim rngInput As Range, rngOutput As Range
Application.ScreenUpdating = False
Set rngInput = Range("A1:A5") '<~~ Input Range
Set rngOutput = Range("B1") '<~~ Output Range
Concatenate rngInput, rngOutput
Application.ScreenUpdating = True
End Sub
Sub Concatenate(rng1 As Range, rng2 As Range)
Dim cl As Range
Dim strOutPut As String
For Each cl In rng1
If strOutPut = "" Then
strOutPut = cl.Value
Else
strOutPut = strOutPut & Delim & cl.Value
End If
Next
rng2.Value = strOutPut
End Sub
Within the context of a worksheet-level code, the following will work. Column 2 is hard-coded, so you might want to pass in a value or otherwise modify it to fit your needs.
Dim rng As Range
Set rng = Me.Columns(2)
Dim row As Integer
row = 1
' Find first row with non-empty cell; bail out if first 100 rows empty
If IsEmpty(Me.Cells(1, 2)) Then
Do
row = row + 1
Loop Until IsEmpty(Me.Cells(row, 2)) = False Or row = 101
End If
If row = 101 Then Exit Sub
' We'll need to know the top row of the range later, so hold the value
Dim firstRow As Integer
firstRow = row
' Combine the text from each subsequent row until an empty cell is encountered
Dim result As String
Do
If result <> "" Then result = result & vbNewLine
result = result & Me.Cells(row, 2).Text
row = row + 1
Loop Until IsEmpty(Me.Cells(row, 2))
' Clear the content of the range
Set rng = Me.Range(Me.Cells(firstRow, 2), Me.Cells(row, 2))
rng.Clear
' Set the text in the first cell
Me.Cells(firstRow, 2).Value2 = result

Resources