VBA-Find Word in Row and output the next column - vba

Amt1 Tax1 Amt2 Tax2 Amt3 Tax3 Amt4 Tax4 Amt5 Tax5 Amt6 Tax6
YQ 25 YR 22 QW 25 TR 58 WR 105 AY 125
YR 102 YQ 25 AY 15 YR 152 WR 55 WQ 120
In Excel, now i want the output in a column for total of YR, if YR comes 5 times in a row the output should give me total of all 5.
can anyone help me with this?

Formula based solution using SUMIFS
=SUMIFS(B2:L2,A2:K2,"YR")
Notice the offset in the ranges: Sum Range is offset 1 column to right of Criteria Range

Welcome to StackOverflow. This is not a code-for-me site and when you ask such questions you should show some kind of effort for solving them.
Having said that, here is a way to solve your problem with a custom formula:
Option Explicit
Public Function OutputMe(rngSelectRange As Range, strOutput As String) As Double
Dim rngCell As Range
For Each rngCell In rngSelectRange
If rngCell = strOutput Then
OutputMe = OutputMe + rngCell.Offset(0, 1).Value
End If
Next rngCell
End Function

You can use the UDF below:
Option Explicit
Function mySumIfs(lRow As Long, Str As String) As Long
Dim LastCol As Long
Dim C As Range
LastCol = Cells(lRow, Columns.Count).End(xlToLeft).Column ' get last column in current row
' loop through all cells in the Range of the Row selected
For Each C In Range(Cells(lRow, 1), Cells(lRow, LastCol))
If C.Value Like Str Then
mySumIfs = mySumIfs + C.Offset(, 1).Value
End If
Next C
End Function
Then, in your Excel Sheet's cell you can just type in the Formula:
=mySumIfs(3,"YR").
3 - indicating the row number
"YR" - the string being searched for
You can also use it from VBA, just use:
Dim SumTest As Long
SumTest = mySumIfs(3, "YR")
Screen-shot of how it is implemented in my Excel Sheet:

Related

how to read matrix in excel vba?

I want to read and store values from 4*4 matrix(2 dimensional array) and use it in my further program. I am talking about VBA for Excel. Data is in Excel sheet and I want to read it through VBA. I am new to this, but learning fast. Please help me doing it.
this is my data in sheet
a 2 5 6
b 6 8 7
c 3 6 9
this is what I want to do
a 0 2 7 13
b 0 6 14 21
c 0 3 9 18
I need to read 3*3 matrix from sheet and transform it to cumulative matrix as shown. (add the previous number and go on).
Basically I am simulating a Markov Chain and needs to count how many times a person go through each stage.
Sub example7()
Dim A As Double, B As Double, C As Double, PC(4, 4) As Double, row As Double, maxrwo As Double, col As Double, maxcol As Double
Range("o5").Activate
For i = 1 To 4
For j = 1 To 4
PC(i, j) = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
Next j
ActiveCell.Offset(1, -4).Select
Next i
Range("T4") = PC(2, 4)
End Sub
If you want to process values in a range you don't need to store them in an array first. You could loop through each cell in the range by using code similar to the below:
Sub LoopThroughRange()
Dim currentCell As Range
Dim desiredRange As Range
Dim outputCell As Range
Dim total As Double
Set outputCell = Range("A6")
Set desiredRange = Range("Sheet1!A1:D4")
'This will add the values of each cell in the range and output the total to cell A6
For Each currentCell In desiredRange
total = total + currentCell.Value
Next currentCell
outputCell.Value = total
End Sub

VBA Autofill formula with a fixed cell reference

I am trying to autofill a formula to a range using vba.
What i am trying to do is to calculate a percentage contribution for each item.
Say i have 2 entries
A1= 4
A2= 6
A3= sum of A1 and A2 =10
What i want is
B1= A1/$A$3 = 40%
B2= A2/$A$3 = 60%
but i am not quite sure how i could locate the last row of A and code it into the
Range("B1").Formula= "=A1/?????"
any ideas would help!
Thanks
Please try this..
Range("B1").FormulaR1C1 = "=RC[-1]/INDEX(C[-1],MATCH(1E+99,C[-1]))"
You need to mention the range with circular references by specifying Row and column no from the active cell respectively like RC[-1]/R3C1
Find the last cell first, then sum it and add the formula to column B
Sub Button1_Click()
Dim LstRw As Long, rng As Range, Sm As Range
LstRw = Cells(Rows.Count, "A").End(xlUp).Row
Set rng = Range("A1:A" & LstRw)
Set Sm = Cells(LstRw + 1, 1)
Sm = Application.Sum(rng)
rng.Offset(, 1) = "=a1/" & Sm.Address
End Sub

Finding last row in selected numbers of columns, can't use end(xldown)

I have a set of columns ( column : "C:I" on the excel sheet ) which I want to select the last cells of. The issue is that I can't use xldown because there are some blank cells in the beginning of the columns...
How to effectively select the last row anyway? I'¨m trying Range("C1:I1").rows.end(xldown) but it gets stuck right at the beginning at the last non-empty cell after the empty ones.
If the columns are filled in an irregular fashion, then:
Sub qwerty()
Dim N As Long, M As Long, mm As Long
M = 0
For N = 3 To 9
mm = Cells(Rows.Count, N).End(xlUp).Row
If mm > M Then
M = mm
End If
Next N
Cells(M, 1).EntireRow.Select
End Sub
For example:
Note that the attractive:
Sub dural()
Range("C:I").Cells.SpecialCells(xlCellTypeLastCell).Select
Selection.EntireRow.Select
End Sub
Will select row #18 by mistake!
An example which works on a single column:
Sub findLastCellInColumnA()
Dim lstRow As Integer
lstRow = Cells(Rows.Count, 1).End(Excel.xlUp).Row
Cells(lstRow, 1).Select
End Sub

Excel Macro: If Column B contains 12 digits then column C equals 3?

So, I'm trying to figure out how to write an Excel macro to populate Column C with either 3 or a 4 depending on the amount of numbers contained in Column B.
I have searched up and down for the right wording to this, but I keep coming up short.
Basically, I need the macro to look at the number of digits in Column B. If there are 12 digits then the number is a UPC, and if there are 13 then the number is an EAN. I then need the macro to populate Column C with a 3 for UPCs and a 4 for EANs. This needs to be for the entire range of rows in the spreadsheet.
Does anyone have any ideas? Thanks a lot in advance!
You don't need to use a dirty old loop, try this (much faster if you have lots of rows):
Sub HTH()
With Sheet1.Range("B1", Cells(Rows.Count, "B").End(xlUp)).Offset(, 1)
.Formula = "=IF(LEN(TRIM(B1))=12,3,IF(LEN(TRIM(B1))=13,4,""""))"
.Value = .Value
End With
End Sub
Or use a user defined function, which has the advantage of changing when the data in column B is updated.
Better yet just use a formula, you don't really need VBA.
Alternative VBA Method (looping the fast way):
Sub HTH()
Dim vArray As Variant
Dim lCnt As Long
With Range("B1", Cells(Rows.Count, "B").End(xlUp))
vArray = .Value
For lCnt = 1 To UBound(vArray, 1)
Select Case Len(Trim(vArray(lCnt, 1)))
Case 12: vArray(lCnt, 1) = 3
Case 13: vArray(lCnt, 1) = 4
Case Else:
End Select
Next lCnt
.Offset(, 1).Value = vArray
End With
End Sub
You can get the length of a cell's value by using Len() like this Len(Range("A1")) for example.
Now you just need to loop through your column and look at each value. If you look for the last used cell and loop only through that range your loop will be faster.
Here is how I would do it:
sub TestUPC()
With ActiveSheet
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
Dim rRng As Range
Set rRng = Range("B1:B" & LastRow)
For Each cell In rRng.Cells
If Len(Trim(cell))=12 then
cell.Offset(0, 1).Value = 3
ElseIf Len(Trim(cell))=13 then
cell.Offset(0, 1).Value = 4
End If
Next
End Sub
An in cell equation could look like this:
=IF(LEN(B1)=12,3,IF(LEN(B1)=13,4," "))
As suggested in the comments you might want to test for spaces depending on your data:
=IF(LEN(TRIM(A1))=12,3,IF(LEN(TRIM(A1))=13,4," "))

How to split dates with VB in Excel

Facing such a problem when hadling with excels again...
I have an excel table with such cloumns
People Date
-------------------------
A 01/01/2013 - 05/01/2013
B 03/05/2013
C 08/06/2013
What I want to produce (For example A)
People Individual Date
-------------------------
A 01/01/2013
A 02/01/2013
A 03/01/2013
A 04/01/2013
A 05/01/2013
The year will be constant at 2013 and month are more or less kept constant as well.
Can someone give idea on how to achieve this?
Sub ExpandDates()
Dim rCell As Range
Dim i As Long
Dim vaDates As Variant
Dim rNext As Range
'Loop through the cells that contain dates or date ranges
For Each rCell In Sheet1.Range("B2:B4").Cells
'If there's a space, hyphen, space in the cell, it's a date range
If InStr(1, rCell.Value, " - ") > 0 Then
'Split the cell contents on space, hyphen, space
vaDates = Split(rCell.Value, " - ")
'Loop through the days of the range of dates
For i = CDate(vaDates(0)) To CDate(vaDates(1))
'Find the next blank cell in column E to record the results
Set rNext = Sheet1.Cells(Sheet1.Rows.Count, 5).End(xlUp).Offset(1, 0)
'Write column A to column E
rNext.Value = rCell.Offset(0, -1).Value
'Create a new date in column B using the month that the loop is currently processing
rNext.Offset(0, 1).Value = CDate(i)
Next i
'If no hyphen, it's just a date, so create one line in column E
Else
Set rNext = Sheet1.Cells(Sheet1.Rows.Count, 5).End(xlUp).Offset(1, 0)
rNext.Value = rCell.Offset(0, -1).Value
rNext.Offset(0, 1).Value = rCell.Value
End If
Next rCell
End Sub
Theory: Check the length of the cell. If the cell is longer than 10 characters, use the SPLIT function to get the 2 dates. Set the months equal to a variable, and do a loop based on those months to calculate the dates between them. You would probably store those dates in an array. Then write the array to the spreadsheet and move to the next cell to start the process over.
EDIT:
Sub prSplit()
If len(ActiveCell.Value) > 10 Then
Dim arr() As String
arr = Trim(Split(ActiveCell.Value, "-"))
For i = LBound(arr) To UBound(arr)
MsgBox arr(i)
Next
End If
End Sub
You can start with this and tweak the code until you get it. I just don't have the time to do the whole thing. Sorry. :o(