extract column range from formula in excel using macro - vba

Sub AddNameNewSheet1()
Dim wsToCopy As Worksheet, wsNew As Worksheet
Dim Newname As String
Newname = InputBox("Number for new worksheet?")
Set wsToCopy = ThisWorkbook.Sheets("Sheet1")
Set wsNew = ThisWorkbook.Sheets.Add
If Newname <> "" Then
wsNew.Name = Newname
End If
wsToCopy.Cells.Copy wsNew.Cells
Dim cell As Range
Dim bIsNumeric As Boolean
Dim testFormula As String
bIsNumeric = False
For Each cell In wsNew.Range("A1:M40")
If cell.HasFormula() = True Then
If bIsNumeric Then
If testFormula = CStr(cell.Formula) Then
cell.Value = "<"
Else
testFormula = cell.Formula
cell.Value = "F"
End If
Else
testFormula = cell.Formula
cell.Value = "F"
End If
bIsNumeric = True
ElseIf IsNumeric(cell) = True Then
bIsNumeric = False
If Len(cell) > 0 Then
cell.Value = "N"
End If
Else
bIsNumeric = False
cell.Value = "L"
End If
Next cell
End Sub
I want to extract column and row that applied in formula. For example,
if formula is =SUM(A10:F10) then I want both A10 and F10 then I remove that is there any way to find out that.
My actual purpose is finding formula without column and row value.
thanks in advance.

If you want to get A10 and F10 from the formula, you can use this, passing your range to strRange:
Sub Extract_Ranges_From_Formula()
Dim strRange As String
Dim rCell As Range
Dim cellValue As String
Dim openingParen As Integer
Dim closingParen As Integer
Dim colonParam As Integer
Dim FirstValue As String
Dim SecondValue As String
strRange = "C2:C3"
For Each rCell In Range(strRange)
cellValue = rCell.Formula
openingParen = InStr(cellValue, "(")
colonParam = InStr(cellValue, ":")
closingParen = InStr(cellValue, ")")
FirstValue = Mid(cellValue, openingParen + 1, colonParam - openingParen - 1)
SecondValue = Mid(cellValue, colonParam + 1, closingParen - colonParam - 1)
Debug.Print FirstValue
Debug.Print SecondValue
Next rCell
End Sub
It does a Debug.Print of the two returned values.

Related

VBA: Highlighting Specific Text (Case Sensitive to Case Insensitive)

The below VBA code is to highlight text (Case Sensitive) in cells. May I know how I can edit the VBA code below to become Case Insensitive?
Sub HighlightStrings_CaseSensitive_AllowForeignText_NotExactText()
Dim xHStr As String, xStrTmp As String
Dim xHStrLen As Long, xCount As Long, I As Long
Dim xCell As Range
Dim xArr
On Error Resume Next
xHStr = Application.InputBox("What are the words to highlight:", "Word Higlighter")
If TypeName(xHStr) <> "String" Then Exit Sub
Application.ScreenUpdating = False
For Each xCell In Selection
Dim varWord As Variant
For Each varWord In Split(xHStr, Space$(1))
xHStrLen = Len(varWord)
xArr = Split(xCell.Value, varWord)
xCount = UBound(xArr)
If xCount > 0 Then
xStrTmp = ""
For I = 0 To xCount - 1
xStrTmp = xStrTmp & xArr(I)
xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.ColorIndex = 39
xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.Bold = True
xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.Italic = True
xStrTmp = xStrTmp & varWord
Next
End If
Next varWord
Next xCell
Application.ScreenUpdating = True
End Sub

Create VBA function based on user-defined function

Thanks to all friends who helped me on my question how to calculate specific cells in excel
Now, I need help to code that excel function in VBA
The function is : =SUM(IFERROR(VALUE(IF(LEN(H27:Q27)=4,IF(ISNUMBER(SEARCH("b",LEFT(H27:Q27,2))),RIGHT(H27:Q27,1),LEFT(H27:Q27,1)),H27:Q27)),0))
Thanks in advance
Here you go:
Public Function GetTotal(rng As Range) As Long
Dim tot As Long
Dim celString As String
Dim t1String As String, t2String As String
For Each cel In rng
If IsNumeric(cel) Then
tot = tot + cel.Value
ElseIf Len(cel.Value) = 4 Then
celString = cel.Value
t1String = Left(celString, 2)
If InStr(1, t1String, "b") = 0 Then
t2String = Left(celString, 1)
Else
t2String = Right(celString, 1)
End If
tot = tot + t2String
End If
Debug.Print tot
Next
GetTotal = tot
End Function
You have to give range as input.
See the image below:
I think this function implements the formula. It's very difficult to test without your original set of data in the cells. Note the function is called from the Foo sub-routine below - so you can pass in a variable range to the function. Hope that helps.
Function DoIt(rng As Range)
' VBA implementation for
'=SUM(IFERROR(VALUE(IF(LEN(H27:Q27)=4,IF(ISNUMBER(SEARCH("b",LEFT(H27:Q27,2))),RIGHT(H27:Q27,1),LEFT(H27:Q27,1)),H27:Q27)),0))
Dim dblResult As Double
Dim rngCell As Range
Dim intLength As Integer
Dim strFragment1 As String
Dim strFragment2 As String
Dim intPos As Integer
'set result
dblResult = 0
'loop for the array formula
For Each rngCell In rngTarget
'check value length = 4
intLength = Len(rngCell.Value)
If intLength = 4 Then
'get bit of string and check for 'b' in string
strFragment1 = Left(rngCell.Value, 2)
'search for location of b in cell - use InStr for SEARCH
intPos = InStr(1, strFragment, "b", vbBinaryCompare)
If intPos <> 0 Then
'b in fragment
strFragment2 = Right(rngCell.Value, 1)
Else
'b not in fragment
strFragment2 = Left(rngCell.Value, 1)
End If
'2nd fragment should be a number? use IsNumeric for ISNUMBER and Val for VALUE
If IsNumeric(strFragment2) Then
dblResult = dblResult + Val(strResult)
End If
Else
'cell value length <> 4
'add cell value to result if is numeric - use IsNumeric for ISNUMBER and Val for VALUE
If IsNumeric(rngCell.Value) Then
dblResult = dblResult + Val(rngCell.Value)
End If
End If
'next cell
Next rngCell
'return sum
DoIt = dblResult
End Function
Sub Foo()
Dim rngTarget As Range
Set rng = Sheet1.Range("H27:Q27")
Debug.Print DoIt(rng)
End Sub

How to get particular values from single cell and put into different cells in Excel VBA

I need to do it for more than 1000 cells, to read the particular data and to put under respective cells using Excel VBA.
Example:
Name Age No. .. .
abc 14 123454 ------>this from single cell
Which contains like Name: abc,Age: 14, No: 123454
This should be a good start :
Sub Split_N_Copy()
Dim InFo()
Dim InfSplit() As String
InFo = ActiveSheet.Cells.UsedRange.Value2
Sheets.Add after:=Sheets(Sheets.Count)
For i = LBound(InFo, 1) To UBound(InFo, 1)
'Here I put InFo(i,1), "1" if we take the first column
InfSplit = Split(InFo(i,1), ",")
For k = LBound(InfSplit) To UBound(InfSplit)
Sheets(Sheets.Count).Cells(i + 1, k + 1) = InfSplit(k)
Next k
Next i
End Sub
I write a function based on , for separator sign and : for equal sign, that search a range of data that first row contains headers:
Function UpdateSheet(allData As String, inRange As Range)
Dim strData() As String
Dim i As Long, lastRow As Long
Dim columnName As String, value As String
Dim cell As Range
'You need to change this to finding last row like this answer:
'http://stackoverflow.com/a/15375099/4519059
lastRow = 2
strData = Split(allData, ",")
For i = LBound(strData) To UBound(strData)
columnName = Trim(Left(strData(i), InStr(1, strData(i), ":") - 1))
value = Trim(Mid(strData(i), InStr(1, strData(i), ":") + 1))
For Each cell In inRange
If cell.Cells(1, 1).Rows(1).Row = 1 Then
If cell.Cells(1, 1).value Like "*" & columnName & "*" Then
inRange.Worksheet.Cells(lastRow, cell.Columns(1).Column).value = value
End If
End If
Next
Next
End Function
Now you can use that function like this:
Sub update()
Call UpdateSheet("Name: abc,Age: 14, No: 123454", Sheets(1).UsedRange)
End Sub
Private Sub CommandButton1_Click()
lastRow = Sheet1.Cells(Sheet1.Rows.Count, "G").End(xlUp).Row
Dim i As Integer
i = 2
For i = 2 To lastRow
Dim GetData As String
GetData = Sheet1.Cells(i, 7)
Call UpdateSheet(GetData, Sheets(1).UsedRange, i)
Next
End Sub
Function UpdateSheet(allData As String, inRange As Range, rowno As Integer)
Dim strData() As String
Dim i As Long, lastRow As Long
Dim columnName As String, value As String
Dim cell As Range
strData = Split(allData, ",")
For i = LBound(strData) To UBound(strData)
Value1 = Trim(Mid(strData(i), InStr(1, strData(i), ":") + 1))
If Value1 <> "" Then
columnName = Trim(Left(strData(i), InStr(1, strData(i), ":") - 1))
value = Trim(Mid(strData(i), InStr(1, strData(i), ":") + 1))
For Each cell In inRange
If cell.Cells(1, 1).Rows(1).Row = 1 Then
If cell.Cells(1, 1).value Like "*" & columnName & "*" Then
inRange.Worksheet.Cells(rowno, cell.Columns(1).Column).value = value
End If
End If
Next
End If
Next
End Function

VBA To Increment Sheets With The Same Name By 1

I currently have a spreadsheet that parses a HL7 message string using "|" as a delimiter. The String that comes before the first "|" becomes the sheet name (Segment). The code executes on each line of the string (Each segment is parsed). The problem is that sometimes there are multiple segments with the same name. So instead of a new sheet being created, all segments are lumped into the same sheet with that name. What I am trying to do is have the code create a new sheet for each segment and if there it is already present, add sheet name with an incremented number.
Sample Message:
MSH|^~\&|SR|500|CL|500|20140804150856-0500||SIU^S14|5009310|P|2.3|||AL|NE|USA
SCH|10262|10262|""|S14^(SCHEDULED)^L|44950^APPENDECTOMY^C4||^^^201408081345-0500^^^^^^2||30|MIN^MINUTES|^^^201408081345-0500^201408081415-0500|10000000034^ROISTAFF^CHIEF^O||||||||
PID|1|5000|50^^^USVHA&&0363^NI^FACILITY ID&500&L^^20140804~666^^^USSSA&&0363^SS^FACILITY ID&500&L~^^^USDOD&&0363^TIN^VA FACILITY ID&500&L~^^^USDOD&&0363^FI^FACILITY ID&500&L~736^^^USVHA&&0363^PI^VA FACILITY ID&500&L|736|DATA^PATIENT^^^^^L||19540214|M|||123 main Street^^SW RS^FL^33332^USA^P^^~^^^^^^N|||||||4221^764|666|||||N||||||N||
PV1|1|I|||||||||||||||||||||||||||||||||||||500|
OBX|1|CE|^SPECIALTY^||^GENERAL||||||S|||||
OBX|2|CE|^PATIENT CLASS^||^INPATIENT^L||||||S|||||
DG1|1|I9|540.1|ABSCESS OF APPENDIX||P
DG1|2|I9||APPENDICITIS||PR
RGS|1|A|
AIS|1|A|44950^APPENDECTOMY^C4||||
AIP|1|A|1000^PHYSICIAN^KT^|^SURGEON^99||||PENDING
AIP|2|A|1000^NURSE^ONE^|^1ST ASST.^99||||PENDING
AIP|3|A|1000^NURSE^TWO^|^2ND ASST.^99||||PENDING
AIP|4|A|1000^ATTENDING^ONE^|^ATT. SURGEON^99||||PENDING
AIP|5|A|115^DATA^PROVIDERONE^|^PRIN. ANES.^99||||PENDING
AIP|6|A|1000^DATA^PATHOLOGIST^|^ANES. SUPER.^||||PENDING
AIL||500^^^OR1|^OPERATING ROOM||||PENDING
Option Explicit
Const HL7_DELIMITER_FIELD = "|"
Const HL7_DELIMITER_SEGMENT = vbLf
Sub DoHL7Parsing(sMessage As String)
Dim vSegments As Variant, vCurSeg As Variant
Dim vFields As Variant, rCurField As Range, iIter As Integer
Dim wsSeg As Worksheet
vSegments = VBA.Split(sMessage, HL7_DELIMITER_SEGMENT)
For Each vCurSeg In vSegments
vFields = VBA.Split(vCurSeg, HL7_DELIMITER_FIELD)
If WorksheetExists(vFields(0), ThisWorkbook) Then
On Error Resume Next
For iIter = 1 To UBound(vFields)
Set rCurField = ThisWorkbook.Worksheets(vFields(0)).Range("A65536").End(xlUp).Offset(1, 0)
rCurField.Value = vFields(0)
rCurField.Offset(0, 1).Value = (rCurField.Row - 1)
rCurField.Offset(0, 2).NumberFormat = "#"
rCurField.Offset(0, 2).Value = vFields(iIter)
Next iIter
On Error Resume Next
ElseIf Not WorksheetExists(vFields(0), ThisWorkbook) Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = vFields(0)
For iIter = 1 To UBound(vFields)
Set rCurField = ThisWorkbook.Worksheets(vFields(0)).Range("A65536").End(xlUp).Offset(1, 0)
rCurField.Value = vFields(0)
rCurField.Offset(0, 1).Value = (rCurField.Row - 1)
rCurField.Offset(0, 2).NumberFormat = "#"
rCurField.Offset(0, 2).Value = vFields(iIter)
Next iIter
'MsgBox "Invalid or unkown segment: " & vFields(0)
End If
Next vCurSeg
On Error Resume Next
End Sub
Public Function WorksheetExists(ByVal WorksheetName As String, Optional InWorkbook As Workbook) As Boolean
Dim Sht As Worksheet
WorksheetExists = False
If Not InWorkbook Is Nothing Then
For Each Sht In InWorkbook.Worksheets
If Sht.Name = WorksheetName Then WorksheetExists = True
Next Sht
Else
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name = WorksheetName Then WorksheetExists = True
Next Sht
End If
On Error Resume Next
End Function
The trick here is to just count the number of sheets whose Left(ShtName,3) value is equal to vFields(0). Based on the count, add 1 and append to end of vField(0). With this approach, you don't even need the dirty On Error Resume Next because you won't be targeting the same sheet twice, which can bring down your line count considerably.
For the sheet counting, add the following function to your module:
Function CountSheetsWithName(ShtName As String) As Long
Dim WS As Worksheet, Res As Long
Res = 0
For Each WS In ThisWorkbook.Worksheets
If Left(WS.Name, 3) = ShtName Then
Res = Res + 1
End If
Next
CountSheetsWithName = Res
End Function
Update your DoHL7Parsing subroutine as follows:
Sub DoHL7Parsing(sMessage As String)
Dim vSegments As Variant, vCurSeg As Variant
Dim vFields As Variant, rCurField As Range, iIter As Integer
Dim wsSeg As Worksheet, sShtName As String
vSegments = VBA.Split(sMessage, HL7_DELIMITER_SEGMENT)
Application.ScreenUpdating = False
For Each vCurSeg In vSegments
vFields = VBA.Split(vCurSeg, HL7_DELIMITER_FIELD)
For iIter = 1 To UBound(vFields)
sShtName = vFields(0) & (CountSheetsWithName(CStr(vFields(0))) + 1) ' Append the count + 1 to end of name.
Sheets.Add(After:=Sheets(Sheets.Count)).Name = sShtName
Set rCurField = ThisWorkbook.Worksheets(sShtName).Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
rCurField.Value = vFields(0)
rCurField.Offset(0, 1).Value = (rCurField.Row - 1)
rCurField.Offset(0, 2).NumberFormat = "#"
rCurField.Offset(0, 2).Value = vFields(iIter)
Next iIter
Next vCurSeg
Application.ScreenUpdating = True
End Sub
Result:
Hope this helps.

search strings in cell

I have multiple values in cell A1 which are separated by a ';'. Some of the same values may be in cell B1. I need to search the values in cell A1 using those in cell B1. All the values that are not found then need to presented in cell C1.
Eg - Cell A1 ( Apple;Orange;Cherry) cell B1 (Apple;Orange;) cell c1 need to reflect "Cherry" as not found
I tried this code:
Sub Splitvalue()
Dim str, mystr As Variant
Dim tp As Integer
str = Split(Range("A1").Value, ";")
For tp = LBound(str) To UBound(str)
mystr = str(tp)
Next
End Sub
Set up your sheet1 like this
the use this code
Option Explicit
Sub Splitvalue()
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Dim c As Range
Dim A As Variant, B As Variant
Dim i As Long, j As Long
Dim x As Boolean
Columns(3).ClearContents
For Each c In Range("A1:A" & lastRow)
A = Split(c, ";")
B = Split(c.Offset(0, 1), ";")
For i = LBound(A) To UBound(A)
For j = LBound(B) To UBound(B)
If A(i) = B(j) Then
x = True
Exit For
Else
x = False
End If
Next j
If Not x Then
If IsEmpty(c.Offset(0, 2)) Then
c.Offset(0, 2) = A(i)
Else
c.Offset(0, 2).Value = c.Offset(0, 2).Value & ";" & A(i)
End If
End If
Next i
Next
End Sub
and your results should look like this
Why not just split the second cell like you split the first cell? Then see if you find each element of A1 in B1, otherwise output to C1?
This is not elegant, but will work:
Sub Splitvalue()
Dim str, mystr As Variant
Dim stri As Variant
Dim tp As Integer
str = Split(Range("A1").Value, ";")
str2 = Split(Range("B1").Value, ";")
For tp = LBound(str) To UBound(str)
mystr = str(tp)
'Debug.Print mystr
Dim found As Boolean
found = False
For Each stri In str2
'Debug.Print stri
If stri = mystr Then
found = True
End If
Next stri
If found = False Then
Debug.Print mystr
End If
Next
End Sub
One way:
dim needle() as string: needle = split(Range("B1").Value, ";")
dim haystack as string: haystack = ";" & Range("A1").Value & ";"
dim i as long
for i = 0 To ubound(needle)
haystack = replace$(haystack, ";" & needle(i) & ";", ";")
next
If len(haystack) = 1 then haystack = ";;"
Range("C1").Value = Mid$(haystack, 2, Len(haystack) - 2)