Insert formula to sum from current and last worksheet - excel

I have a workbook where I need to be creating new sheets in which I need to change the formula of cells from I8 to I39 to be the sum of H8 and I8 of the previous sheet. So in sheet3 I8 value must be =H8+sheet2!I8.
Dim aCell As String
Dim bCell As String
Dim i As Integer
For i = 8 To 39
aCell = Cells(i, 7).Address
bCell = Cells(i, 8).Address '<--need this but on the previus sheet
Cells(i, 9).Formula = "= & aCell & "+" & bCell" '<--i need the formula to be "=i,8+i,8(previus sheet)
Next i
This was as far as I could get, you can see what I was trying to do but I don't know the syntax.

Borrowing a bit from Scott Craner's comment:
Dim PrevSheet As Integer
PrevSheet = Application.ActiveSheet.Index - 1
ActiveSheet.Range("I8:I39").FormulaR1C1 = "=RC-1 + " & Sheets(PrevSheet).Name & "!RC"
This works as long as you have the correct sheet selected, and the indexes of the sheets are defaults, that is Sheet1 is indexed 1, Sheet2 is indexed 2.
If you add or delete sheets, this might not always be the case.

You may be able to rely on the current Worksheet.Index property to retrieve the name of the previous sheet. The Range.Address property can supply the rest.
Sub newFormulas()
Dim i As Long
With Worksheets("Sheet3")
For i = 8 To 39
.Cells(i, 9).Formula = _
Chr(61) & .Cells(i, 8).Address(0, 0) & Chr(43) & _
Worksheets(.Index - 1).Range(.Cells(i, 9).Address).Address(0, 0, external:=True)
Next i
End With
End Sub
I've used soe ASCII codes with the Chr function to avoid having to deal with a lot of quoted string parts.

Related

If value matches from list, insert corresponding value below

Attempting to write some vba but not having much luck. I have column A with a whole list of values that I am counting and looping through. For Each value in column A, there can be a match in range C:D. If a value in column A matches a value in column C. I want to insert the corresponding value in column D below the Column A value. I am not too certain on what my IF then statement should look like. I have my counter and loop... I am just unsure where to go with the middle portion of the code.
Sub SetListOrder()
Dim wp As Worksheet
Dim ef As Long
Set wp = Workbooks("Packing Slip FIXED").Worksheets("Locate Order")
ef = wp.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To ef
IF (UNSURE WHAT TO PLACE HERE!) THEN
Next i:
End Sub
Edit: adding sample data
Sample Data screenshot
In this example, I would like to insert a new row under the value in "A" where A=C. ie. Range in column "A" = Range in Column "C". I would like to then insert the value from "D". The new order in rows 4-6 would be:
Range
Order Group 1
2604291
I already have written the code to manually move my sheets around to follow the specific order once I am able to get the names in said order.
I agree with #BigBen that the simpler approach would be to insert a formula in column D that only replicates the column A value when a match is detected. Such a formula would probably look like the following -
=IF($A1=$C1,$A1,"")
This would be copied into cell D2 of your column and copied down as far as needed.
However, if you did want to achieve this with VBA and I have noted you used the word insert a value (as opposed to simple enter a value or copy & paste a value) then this could be your approach -
Sub SetListOrder()
Dim wp As Worksheet
Dim ef As Long
Dim i As Long
Set wp = Workbooks("Packing Slip FIXED").Worksheets("Locate Order")
ef = wp.Range("A" & Rows.Count).End(xlUp).Row
For i = ef To 1 Step -1
If wp.Range("A" & i).Value = wp.Range("C" & i).Value Then
wp.Range("D" & (i + 1)).Insert xlShiftDown
wp.Range("D" & (i + 1)).Value = wp.Range("A" & i).Value
Else
End If
Next i
End Sub
This approaches the problem in reverse by going up your column instead of going down. Note that by inserting your data, will cause each previous value to move down as well. If you don't want this, then simply erase the .Insert line and it will enter the value instead of inserting a cell.
Modify the below code and use:
Formula:
=IFNA(VLOOKUP(A1,$C$1:$D$5,2,0),"Missing")
VBA Code:
Option Explicit
Sub test()
Dim rngSearch As Range, rngFound As Range
Dim LastRowA As Long, LastRowC As Long, i As Long
With ThisWorkbook.Worksheets("Sheet1")
LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
LastRowC = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rngSearch = .Range("C1:D" & LastRowC)
For i = 1 To LastRowA
Set rngFound = rngSearch.Find(.Range("A" & i).Value, LookIn:=xlValues, Lookat:=xlWhole)
If Not rngFound Is Nothing Then
.Range("B" & i).Value = .Range("D" & rngFound.Row).Value
Else
.Range("B" & i).Value = "Missing"
End If
Next i
End With
End Sub
Result:

VBA - Find Row from Multiple Criteria

I've been down this road before. Match function worked when I was using a single criteria, but I'm not able to use it properly using two criterias.
My current procedure looks on the NR_Qualtrics page to find a match on CaseID and Email. Because the columns for these can be different based on each document I get, I have procedure that identifies the row and returns which range CaseID and Email is in.
The next thing I'm doing in this function is iterating through each of the rows in NonResidential sheet trying to find a match on CaseID and Email. I need the function to return the row that the match was found on and report that in column O. Currently, I'm still stuck trying to find the matching columns. I keep getting Error 2015 and Error 2029 when I'm debugging. I'm sure that the matches exist when I look through it manually. I'm not sure what I'm doing wrong with my procedure. Can you please help?
Sub NonResFindMultipleProviders()
'This function finds any duplicate Case IDs for NR providers where they had surveys
'This function needs to run before NonRes_ChkSurveyRcd
'If there are duplicates, it will indicate that in the Notes Column (N)
'If a duplicate exists, then it must match on Email and CaseID and show the value of Yes-NR_Qualtrics Row XX/No in Survey Recieved (Column O)
Application.ScreenUpdating = False
Dim r, lastRow, rowMatch As Long
Dim colCaseID, colEmail, colResponseID As Long
Dim rngCaseID, rngEmail, rngResponseID As Range
Dim valEmail, valCaseID As String
Dim result As Variant
Dim shtNR As Worksheet
Dim shtQNR As Worksheet
Sheets("NonResidential").Select
lastRow = getLastRow
Range("A2").Select
Set shtNR = ThisWorkbook.Sheets("NonResidential")
Set shtQNR = ThisWorkbook.Sheets("NR_Qualtrics")
colCaseID = FindColHeaderWText("NR_Qualtrics", "ExternalDataReference")
Set rngCaseID = Worksheets("NR_Qualtrics").Columns(colCaseID)
colEmail = FindColHeaderWText("NR_Qualtrics", "EmailAddress")
Set rngEmail = Worksheets("NR_Qualtrics").Columns(colEmail)
'colResponseID = FindColHeaderWText("NR_Qualtrics", "ResponseID")
'Set rngResponseID = Worksheets("NR_Qualtrics").Columns(colResponseID)
'The Notes field(column N) shows the duplicates. Find matches on CaseID AND Email
''Not (IsError(Application.Match(Cells(r, 1).Value, rng, 0))) And
For r = 2 To lastRow
valCaseID = Cells(r, 1).Value 'Column A (1) has CaseIDs
valEmail = Cells(r, 12).Value 'Column L (12) has emails
result = shtNR.Evaluate("MATCH(" & valCaseID & "&" & valEmail & ",rngCaseID&rngEmail,0)")
If (Not IsError(result)) Then 'Mark only if Notes - Column N (13) is marked with a duplicate - Need to put this in next. RN, just evaluate everything
Cells(r, 15).Value = "Yes" 'Column O (14) Survey Recieved marked with Yes
End If
Next r
'Cleanup - Remove the words duplicate
'Columns("N:N").Select
'Selection.Replace What:="Duplicate", Replacement:="", LookAt:=xlWhole, _
' SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
' ReplaceFormat:=False
Application.ScreenUpdating = True
End Sub
Here's an example that matches based on 3 criteria. Try dropping your ranges and criteria into this:
Sub MatchMultipleCritera()
' Cells containing the values to match
Dim criteria1 As Range, criteria2 As Range, criteria3 As Range
Set criteria1 = Range("A1")
Set criteria2 = Range("B1")
Set criteria3 = Range("C1")
' Ranges containing the values to be checked against the match values above.
Dim rng1 As Range, rng2 As Range, rng3 As Range
Set rng1 = Range("Table1[Item]")
Set rng2 = Range("Table1[Active]")
Set rng3 = Range("Table1[Quanitity2]")
MsgBox "Row " & Evaluate("=MATCH(1,(" & criteria1.Address & "=" & rng1.Address & ")*(" & criteria2.Address & "=" & rng2.Address & ")*(" & criteria3.Address & "=" & rng3.Address & "))")
End Sub
In this example:
Cells A1, B1 and C1 contain the values I am matching.
I am looking in a table (Excel.ListObject) named "Table1" that has columns "Item", "Active" and "Quantity".
rng1 is checked for the value in criteria1, rng2 for criteria2, etc.
The result is the row number.
This is a VBA modification of this ExcelJet article using array formulas. The Evaluate function evaluates formulas as array formulas by default

VBA to Create Dynamic Named Ranges

I am trying to create named ranges of cells named after the top left cell in each range. This shows what I mean:
Here, I want to have 4 named ranges (Names A, Names B, Names C, Names D) so I can reference them. Is there a way to have excel look for any cell in Column B that starts with "Names" and have it cut off the range when it hits the next cell that starts with "Names"? I apologize if this is not possible, I am still new to excel and not sure if this is doable. Any help is appreciated!
This is a quick thrown together script to provide the idea of how to approach this. By no means is it pretty, but does show the steps. This can be a lot more complexly written, ie to work with all cells, not start after the first instance of names (See Range("B3") for start, and Range("B4") for starting the looping of cells)
Sub DefineRanges()
Dim rngStart As Range
Set rngStart = Range("B3")
Dim NamedRangeCount As Integer
NamedRangeCount = 0
Dim NameRangeName As String
Dim LastRow As Integer
For Each cell In Range("B4:B18")
If LCase(Left(cell.Value, 5)) = "names" Then
NameRangeName = "Name_" & NamedRangeCount
ActiveWorkbook.Names.Add Name:=NameRangeName, RefersToLocal:=Range(rngStart.Address & ":D" & cell.Row - 1)
Set rngStart = Range("B" & cell.Row)
NamedRangeCount = NamedRangeCount + 1
End If
LastRow = cell.Row
Next
NameRangeName = "Name_" & NamedRangeCount
ActiveWorkbook.Names.Add Name:=NameRangeName, RefersToLocal:=Range(rngStart.Address & ":D" & LastRow)
End Sub

How to select mutiple values from excel single cell

I have excel cell having multiple rows of data with image url.
Now I want to select all images having 1500 value. So basically I want to select row starting with http and ending 1500.jpg.
Please not that in my single cell values are also other than 1500.jpg.Sample data is given below
colorImages': { 'initial': [{"hiRes":"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UL1500_.jpg","variant":"MAIN","lowRes":null},{"hiRes":"https://images-na.ssl-images-amazon.com/images/I/716mECZ9JDL._UL1500_.jpg","thumb":"https://images-na.ssl-images-amazon.com/images/I/313QD20m4WL._SR38,50_.jpg","large""thumb":"https://images-na.ssl-images-amazon.com/images/I/313QD20m4WL._SR38,50_.jpg","large":"https://images-na.ssl-images-amazon.com/images/I/313QD20m4WL.jpg","main":{"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY445_.jpg":[445,117],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY500_.jpg":[500,132],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY550_.jpg":[550,145],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY606_.jpg":[606,160],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY679_.jpg":[679,179],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY741_.jpg":[741,195],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY879_.jpg":[879,231]},
Assuming data is in Column A starting from Cell A2 and all the URLs ending with 1500.jpg needs to be displayed in adjacent columns i.e. same row Column B, Column C, Column D,.... then following might help.
Sub Demo()
Dim ws As Worksheet
Dim lastRow As Long, colIndex As Long
Dim rng As Range, cel
Dim X As Long, DotCount As Long
Dim Pat As String, EndPat As String, Parts() As String
Set ws = ThisWorkbook.Worksheets("Sheet3") 'change Sheet3 to your data sheet
With ws
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'get last row with data in Column A
For Each cel In .Range(.Cells(2, 1), .Cells(lastRow, 1)) 'loop through A2 to last cell with data in Column A
colIndex = 1
Pat = "*[!&-;?-[_a-z~=!" & Chr$(1) & "]."
EndPat = "[!&-;?-[_a-z~=!" & Chr$(1) & "]*"
Parts = Split(cel.Value, """") 'split cell value into an array
For X = 0 To UBound(Parts)
If Parts(X) Like "*?.?*" Then
DotCount = Len(Parts(X)) - Len(Replace(Parts(X), ".", ""))
If """" & Replace(Parts(X), "]", Chr$(1)) & """" Like Application.Rept(Pat, DotCount) & EndPat Then
Parts(X) = ""
ElseIf Right(Parts(X), 8) <> "1500.jpg" Then
Parts(X) = ""
Else
cel.Offset(0, colIndex) = Parts(X) 'display URL
colIndex = colIndex + 1
End If
Else
Parts(X) = ""
End If
Next X
Next cel
End With
End Sub
Derived this solution using Function URLs from here.
This is done easily via VBA, but am not expert in that. So I have done some thing for you,just follow the instruction , still it is apply to get only single search entry i.e. means in a cell its find only one 1500.jpg entry.
To get second entry in the same cell you need some effort via change or get substring from the G1 Cell string and repeat the step as explained again.
In A1 Cell, put 1500.jpg
In B1 Cell, put your actual string as you have above
In C1 cell, put formula "=SEARCH(A1,B1)", which find the search 1500 in string
In D1 cell, put formula "=MID(B1,1,C1)", which extract the substring
For E1 we need reverse the string via VBA code - Add Reversestr function (To add this function, see this link)
In F1 cell, put formula "=SEARCH(CHAR(34),E1)", which search " in above reverse string
In G1 cell, put formula "=MID(B1,C1-F1+1,C1)"
Finally you get the string in G1 Cell as "https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._1500.jpg"
For VBa formula, check this links
http://analystcave.com/excel-substring-vba-substring/

How Do I Find The Cells With Contiguous Data In A Row In Excel VBA?

Given the Image... If I know that there is some data starting at Range("B3").
How can I find the cells with contiguous data that is till cell E3? Since F3 is blank G3 onwards should not be considered.
The result could either be a range object (B3:E3) or count of cells( 4 in this case).
By setting B3 as the Active cell and doing..
Range(ActiveCell, ActiveCell.End(xlToRight).Count
I do get the count, however this method is not reliable, in case only B3 has data it counts the cells till the end of the sheet.
Of course this could also be achieved by looping through the cells but I'd rather use a Worksheet Function or some other efficient method.
It seems that you are trying to determine the number of continuous columns used by in a row, starting from cell B3.
The code below will return the values of $B$3:$E$3 and 4 based on your data. If only cell B3 has data, it will return $B$3 and 1.
Sub GetDataArea()
Dim strCellToTest As String
Dim rngMyRange As Range
Dim lngColumns As Long
strCellToTest = "B3"
lngColumns = ActiveWorkbook.ActiveSheet.Range("" & strCellToTest).End(xlToRight).Column - 1
If lngColumns >= 256 Then
Set rngMyRange = ActiveWorkbook.ActiveSheet.Range("" & strCellToTest)
lngColumns = 1
Else
Set rngMyRange = ActiveWorkbook.ActiveSheet.Range _
(strCellToTest & ":" & Range("" & strCellToTest).Offset(0, lngColumns - 1).Address)
End If
MsgBox "Columns: " & lngColumns & vbCr & vbLf & "Range: " & rngMyRange.Address
End Sub
Intersect(Activecell.CurrentRegion, ActiveCell.EntireRow)
Will return B3:E3. Alternatively
If IsEmpty(ActiveCell.Offset(0,1).Value) Then
Set rMyRange = ActiveCell
Else
Set rMyRange = ActiveCell.Parent.Range(ActiveCell, ActiveCell.End(xlToRight))
End If
rMyRange will also return B3:E3
You could use the CurrentRegion property. This returns the range that is contiguous to the specified range. So...
Range("B3").CurrentRegion returns the range B3:E3
Range("B3").CurrentRegion.Columns.Count returns 4
Range("B3").CurrentRegion.Cells.Count also returns 4
However, if you had data in rows 4 and below (let's say you had data in B4:E6), then you would get these results
Range("B3").CurrentRegion returns the range B3:E6
Range("B3").CurrentRegion.Columns.Count returns 4
Range("B3").CurrentRegion.Cells.Count returns 16
Is this what you were after?
I like to use a function that counts columns that contain values until it encounters an empty cell. The return value can be used to set up a FOR NEXT loop to churn through a table. Here is how I would do it:
Sub tester()
Dim Answer
Answer = CountColumns(3, 2)
MsgBox "There are " & Answer & " columns."
End Sub
Public Function CountColumns(ByVal startRow As Integer, ByVal startColumn As Integer)
'Pass starting location in spreadsheet for function to loop through until
'empty cell is found. Return count of columns function loops through
Do While ActiveSheet.Cells(startRow, startColumn).Value <> ""
startColumn = startColumn + 1
Loop
startColumn = startColumn - 1
CountColumns = startColumn
End Function
Depending on how general you need to get, it could be as simple as
Application.WorksheetFunction.Count([b4:e4])
If you want to tie in the ActiveCell, try
Application.WorksheetFunction.Count(intersect(activecell.CurrentRegion, activecell.EntireRow))

Resources