Write a dynamic sum formula vba that takes range from another sheet - excel

screenshot of code
I am trying to calculate sum in cell "I13" of sheet2 with inputs based on the dynamic range.
Formula
range("I13").formula= "=sum('sheet1'!A1:A3)"
works but the range can be dynamic. For this I have used lr to identify the last row in the range
lr=cells(rows.count,1).end(xlup).row
Now, I want to modify the above formula such that in place of A3, it takes last cell. i.e. A&lr
Have tried using range("I13").formula= "=sum('sheet1'!A1:A"&lr)", but it results in error
Sub MMM()
Windows("Template.xlsx").activate
sheets("sheet1").select
range("a1").select
lr=cells(rows.count,1).end(xlup).row
sheets("sheet2").select
'this code works. But want dynamic range
'range("I13").formula = "= SUM('sheet1'!A1:A3)"
range("I13").formula = "= sum('sheet1'!A1:A&lr)"
End Sub

you can try to define the variable:
Option Explicit ' It should be used when you define variable
Sub MMM()
Dim lr as Range ' Define variable
Windows("Template.xlsx").activate
sheets("sheet1").select
range("a1").select
lr=cells(rows.count,1).end(xlup).row
sheets("sheet2").select
range("I13").formula = "= sum('sheet1'!A1:A&lr)"
End Sub

You have to join the string for the formula like this:
"=SUM('Sheet1'!A1:A" & lastRow & ")"
Alternatively:
If you set the whole range to be summed then you can use the Address of this range. The External-parameter returns the sheet name as well.
Sub MMM()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim wsSource As Worksheet: Set wsSource = wb.Worksheets("Sheet1")
Dim wsTarget As Worksheet: Set wsTarget = wb.Worksheets("Sheet2")
Dim rgDataToSum As Range
With wsSource
Set rgDataToSum = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
End With
wsTarget.Range("I13").Formula = "=SUM(" & rgDataToSum.Address(True, True, External:=True) & ")"
End Sub

Related

Pull data from certain WS and paste to another WS

Need help with my code please. I want to search all worksheets in a workbook that contain a specific string in its sheet name to copy cell data of a range and paste as values into a different ws. I keep getting Run-Time error '9' subscript out of range. It highlights Set wsSumm = ThisWorkbook.Sheets("Summary") as the reasoning. I have a Summary tab so I am unsure why it is giving this error.
What I ultimately need to do is take data from A2 of all BL ws and paste into Column A of Summary ws. Then take A1 of all SL ws and paste into Column B of Summary ws. I would need to paste as values. My sheets are named 1-15 as BL, SL (BL1, SL1, BL2, SL2, BL3, SL3, ect) and a Summary ws. Below is what my Workbook looks like and the Code I am using.
[enter image description here][1]
Option Explicit
Sub Macro1()
Dim wsSumm As Worksheet, ws As Worksheet
Dim strCol As String
Dim lngRow As Long
Application.ScreenUpdating = False
Set wsSumm = ThisWorkbook.Sheets("Summary") '<-Sheet name for the data to be concolidated. Change to suit.
For Each ws In ThisWorkbook.Sheets
If ws.Name <> wsSumm.Name Then
strCol = IIf(StrConv(Left(ws.Name, 2), vbUpperCase) = "BL", "A", "B")
lngRow = IIf(StrConv(Left(ws.Name, 2), vbUpperCase) = "BL", 2, 1)
wsSumm.Range(strCol & Rows.Count).End(xlUp).Offset(1, 0).Value = ws.Range("A" & lngRow)
End If
Next ws
Application.ScreenUpdating = True
End Sub

Vlookup VBA Excel

Range("B3").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],'02.09'!C[-1]:C,2,0)"
Range("B3").Select
Selection.FillDown
First:
I'm using the above code to to a Vlookup. If I run this Macro there is no error, but also the column which i did the vlookup has no values.
Second:
In this code im referencing sheet "02.09". But i would like to reference always the second sheet. I haven't found a solution yet.
Thank you all!
VLookup R1C1 Formula in VBA
A Quick Fix
Sub VLookupR1C1()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets(2)
Dim dws As Worksheet: Set dws = wb.Worksheets(1) ' adjust!
With dws.Range("B3") ' reference the first cell
Dim lRow As Long ' the last row in column 'A' (offset '-1')
lRow = .Offset(dws.Rows.Count - .Row, -1).End(xlUp).Row
With .Resize(lRow - .Row + 1) ' reference the (one-column) range
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],'" & sws.Name _
& "'!C[-1]:C,2,0),"""")" ' write the formula to the range
End With
End With
End Sub
The reason that there is no data in your column is that Fill down requires a range; it fills a range with the first cell in the range. The following code will fill down to row 5, you will need to define the last row that you want the formula copying to.
Range("B3").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],'02.09'!C[-1]:C,2,0)"
Range("B3:B5").FillDown

how to copy and paste between 2 different sheets and columns

I would like to be able to copy the selected row from sheet 3 range B: G and paste the cells to sheet 4 column A: F
but when the operation ends I find the formatting in the A: F range and the pasted data in the B: G range Thanks
Sub Elimina_selezione()
Worksheets(3).Activate
ActiveSheet.Unprotect
Call copia_archivio
Worksheets(3).Activate
ActiveCell.EntireRow.Delete
Sheets(3).Protect
End Sub
Sub copia_archivio()
Dim i As Range
Dim rig As Long
Sheets(3).Select
ActiveCell.EntireRow.Copy
Worksheets(4).Activate
ActiveSheet.Unprotect
With Sheets(4).Range("A" & Rows.Count).End(xlUp).Offset(1)
.PasteSpecial Paste:=xlPasteValues, Transpose:=False
With Intersect(.EntireRow, .Parent.Columns("A:F"))
.Interior.ColorIndex = 44
.Borders.LineStyle = XlLineStyle.xlContinuous
End With
End With
End Sub
Better to use range and worksheet variables where possible. The only activation necessary is to get the selection on sheet3, I think. (tested code)
Sub CopyRowFromSheet3to4andDeleteRow()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim wsSrc As Worksheet: Set wsSrc = wb.Worksheets("Sheet3")
Dim wsTgt As Worksheet: Set wsTgt = wb.Worksheets("Sheet4")
wsSrc.Activate 'need to activate it to get its selected range
Dim rSel As Range: Set rSel = wb.Windows(1).Selection 'window(1) is always the active worksheet
Dim iSelRow As Long: iSelRow = rSel.Row
Dim rSrc As Range: Set rSrc = wsSrc.Range("B" & iSelRow & ":G" & iSelRow)
Dim iTgtRow As Long: iTgtRow = wsTgt.Range("A" & wsTgt.Rows.Count).End(xlUp).Row + 1
Dim rTgt As Range: Set rTgt = wsTgt.Range("A" & iTgtRow & ":F" & iTgtRow)
rSrc.Copy rTgt
rTgt.Interior.ColorIndex = 44
rTgt.Borders.LineStyle = XlLineStyle.xlContinuous
Dim rDelSrcRow As Range: Set rDelSrcRow = wsSrc.Range(iSelRow & ":" & iSelRow)
rDelSrcRow.Delete xlShiftUp
End Sub
You are saying that you copy the selected row from sheet 3 range B: G. As far as I understand you are trying to copy not the whole row but only the range of intersection with columns b:g. But your code copies the whole row starting from column A, not B.
You should re-code the range you want to copy and replace "activecell.entirerow" with it.

Copy Paste Columns from one sheet to another sheet based on Autofilter

I am trying to copy data from sheet to another sheet based on a filter.
Based on Column Q where autofilter criteria is "P", I need to copy column T & U from sheet ORD_CS to sheet Namechk.
Here is my code. No error but the entire column is getting copied.
Sub Macro26()
'
'Match Personal Names
'
'
Dim i As Long, LR As Long
Dim sht, sht1 As Worksheet
Set sht = ActiveWorkbook.Worksheets("ORD_CS")
Set sht1 = ActiveWorkbook.Worksheets("Namechk")
sht.Range("A7:AC7").AutoFilter Field:=17, Criteria1:="P"
sht.Range("T7:U99999").Copy
sht1.Range("A1").PasteSpecial
Application.CutCopyMode = False
End Sub
Try this:
sht.Range("T7:U99999").SpecialCells(xlCellTypeVisible).Copy sht1.Range("A1")
instead of
sht.Range("T7:U99999").Copy
sht1.Range("A1").PasteSpecial
Sub filter_paste()
Dim sht, sht1 As Worksheet
Set sht = ActiveWorkbook.Worksheets("ORD_CS")
Set sht1 = ActiveWorkbook.Worksheets("Namechk")
sht.Range("A:AC").AutoFilter Field:=17, Criteria1:="P"
sht.Range("T7:U99999").Copy sht1.Range("A1")
End Sub

excel vba: Range gives Argument Not Optional error message

In excel vba I'm tryin to select a range of values starting in Cell"O2", (O from Oyster) down to the end of the sheet,
I'm trying:
Range("O2", Range.End(xlDown))
But that fails with Argument Not Optional. What am i doing wrong?
I'm using Excel 2010.
Don't use xlDown Declare your Objects and then work with it.
Use this
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim LRow As Long
Dim rng As Range
'~~> Change this to the relevant sheet name
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find last row in Col O which has data
LRow = .Range("O" & .Rows.Count).End(xlUp).Row
'~~> This is your range
Set rng = .Range("O2:O" & LRow)
With rng
'~~> Whatever you want to do
End With
End With
End Sub
To select the range from O2 to the last filled cell in that column, you could use:
Range("O2", Range("O2").End(xlDown)).Select
But that has a few problems, including the fact that it will "stop" at any blanks, and that you should avoid using Select unless absolutely necessary. Also, you should get in the habit of qualifying your ranges, e.g., specifying which worksheet they're in. Given all that, I propose something like this, assuming you wanted to turn the cells in the range red:
Sub test()
Dim LastRow As Long
Dim ws As Excel.Worksheet
Set ws = ActiveSheet
With ws
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
.Range("O2:O" & LastRow).Interior.Color = vbRed
End With
End Sub
Maybe you need
Range("O2", Range("O2").End(xlDown)).Select
?

Resources