Dynamic range in VBA formula multiple worksheets - vba

Let consider the following piece of code, where I inserted an Excel formula to perform a very simple count.
dim wb as Workbook
dim ws as Worksheet
dim ws_a as Worksheet
set wb = ThisWorkbook
set ws = wb.Worksheets("D")
set ws_a = wb.Worksheets("A")
With ws_a
.Range("c2").Formula = _
"ROWS(UNIQUE(FILTER(" & "D"! & Range("c2:c400").Address & "," & _
"IF(" & .Range("a2").Address(0,0) & " =""Empty"","""",""*""& " & .Range("a2").Address(0,0) & " &""*""))"
'following part of code
End With
As you can see, the Range in the Sheet "D" is not dynamic. I'd like to make it dynamic, taking into account the empty cells in the range. Basically, I would need to replace
Range("c2:c400")
with something like
D.Range("c2"),D.Cells(D.Range("c2").SpecialCells(xlCellTypeLastCell).Row, 3))
In the attempt of concatenating strings, I definitely get lost with & and "", so I think this is the problem: my poor knowledge of this type of syntax.
I've also tried to dim and set the range needed (outside the formula), but the code refers to the wrong sheet, as if it could not identify different sheets in the formula.

Dim wb as Workbook, ws as Worksheet, ws_a as Worksheet
Set wb = ThisWorkbook: Set ws = wb.Worksheets("D"): Set ws_a = wb.Worksheets("A")
Dim rngFilter as Range: Set rngFilter = ws_a.Range("c2:C400")
Set rngFilter = Range(rngFilter.Cells(1), rngFilter.SpecialCells(xlCellTypeLastCell))
With ws_a
.Range("c2").Formula = _
"ROWS(UNIQUE(FILTER(" & rngFilter.Address & "," & _
"IF(A2 =""Empty"","""",""*""& A2 &""*""))"
'following part of code
End With

Related

Return parent workbook range of particular sheet

using vlookup function one workbook to another workbook, this code " & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) return the range from first sheet of the wb2, eventhough have set the rage (Rg) from third sheet of wb2 Set Rg = wb2.Sheets(3).Range("A3:Z10000") .. why the rage (Rg) not returning of the third sheet of wb2 and how to return the rage of specific sheet of wb2 ?
Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook
Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")
Application.Workbooks(2).Activate
With ActiveSheet
a = ActiveCell.Column
lastrow = 100
strColumn = Split(ActiveCell.Address, "$")(1)
ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"
ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))
end Sub
You can use the Address with the 4th parameter being xlExternal, it will add the Worksheet object's name, and also the Workbook object's name.
So your FormulaR1C1 line should be:
ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Address(True, True, xlR1C1, xlExternal) & ",6,False)"
Note: your should try to avoid using Activate, ActiveSheet, and ActiveCell, instead use fully qualified Range and Cells objects.
Using the Address is easier, but to address your question, Rg.Parent or Rg.Worksheet gets a reference to the worksheet containing the range. You used Rg.Parent.Parent which is a reference to the workbook. You need both for the formula, assuming you are using a cross-workbook formula.
ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],'[" & Rg.Parent.Parent.Name & "]" & rg.Worksheet.Name & "'!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"

Dim a sheet from variable workbook

Need you help on my macro
I try to vlookup from 2 difference workbook. 1 of my workbook will change name everyday as per date. I already get that part. Now I stuck how to Dim the variable workbook to use in vlookup formula. Here my code
I want to dim OCBReport.
Sub Part_ETA_PLANNER()
'
'Part ETA PLANNER Macro
'
'
'Find OCB PLanner Today
Dim OCBDaily As Workbook
Dim t As Workbook
For Each t In Workbooks
If Left(t.Name, 11) = "OCB_Report_" Then
Set OCBDaily = Workbooks(t.Name)
End If
Next t
'Variable Dim
Dim PartNumber, myRange As Long
Dim OCBReport As Sheets
Set OCBReport = "[ & OCBDaily & ]OCB" ' I got error on this part'
PartNumber = Range("L2").Offset(0, -10).Address(0, 0)
myRange = "'" & OCBReport & "'!C:W"
'Vlookup Part ETA planner
Dim LastRow As Long
LastRow = Sheets("Unfulfilled Daily Report").Range("E" & Rows.Count).End(xlUp).Row
Sheets("Unfulfilled Daily Report").Range("L2").Formula = "=VLOOKUP(" & PartNumber & "," & myRange & ", 21, FALSE)"
Sheets("Unfulfilled Daily Report").Range("L2").AutoFill Destination:=Range("L2:L" & LastRow)
Sheets("Unfulfilled Daily Report").Range("L2:L" & LastRow).Copy
Sheets("Unfulfilled Daily Report").Range("L2:L" & LastRow).PasteSpecial xlPasteValues
Range("B2").Select
End Sub
What you need is a String variable. Also if you put a variable within quotes then it will behave like a string. Also OCBDaily.Name will give you the workbook name which you can encase in "[]"
Change
Dim OCBReport As Sheets
Set OCBReport = "[ & OCBDaily & ]OCB" ' I got error on this part'
to
Dim OCBReport As String
OCBReport = "[" & OCBDaily.Name & "]OCB"
If I understand your part of code correctly, you need to change it to:
Set OCBReport = OCBDaily.worksheets("OCB")
Your attempt tries to set the sheet variable to a string, which give should give an type error. 'OCB' should be the name of the wanted worksheet.
Greetings,
Krossi

Dynamic discontinuous excel ranges in VBA

How can I dynamically extend the number of rows in two columns that I need to copy to another sheet?
First, I identify the number of rows I need to include and store in totrows:
Dim totrows As Integer
With ThisWorkbook.Worksheets("Sheet1")
totrows = .Range("A" & .Rows.Count).End(xlUp).Row
End With
Next, I am trying to extend the two columns of interest ("B" and "G") so that the range includes that totrows rows. For a static example, if totrows=100 then I would have:
With ThisWorkbook.Worksheets("Sheet1")
.Range("B2:B102,G2:G102").copy
End With
I then paste them into my second sheet with:
ThisWorkbook.Worksheets("Sheet2").Range("A2").Paste
.Range("B2:B102,G2:G102").copy
can be written as
.Range("B2:B" & totrows & ",G2:G" & totrows).Copy
Another way without using .Copy or .Paste would be this:
Sub Copy()
Dim wb As Workbook
Dim wsCopy As Worksheet
Dim wsPaste As Worksheet
Dim totrows As Integer
Set wb = Workbooks("Book1.xlsm")
Set wsCopy = wb.Worksheets("Sheet1")
Set wsPaste = wb.Worksheets("Sheet2")
totrows = wsCopy.Range("A" & wsCopy.Rows.Count).End(xlUp).Row
wsPaste.Range("A1:B" & totrows) = wsCopy.Range("A2:A" & totrows, "G2:G" & totrows).Value
End Sub
This way your directly putting the Values into the Range you want.

Copy data data from one worksheet to another with a condition

I'm working on a macro that helps me to copy data from one worksheet to another in Excel with some conditions. I tried the following code; it works, but I got an infinite loop and I was not able to make the condition correctly in the code (I have to copy only the lines with the drop down list displays (complete), actually it's filled with 3 options (complete/cancel/in process)
Sub copier()
Dim ws1 As Worksheet, ws2 As Worksheet, src As Range, dest As Range, i As Integer
Set ws1 = Worksheets("Workload - Charge de travail")
Set ws2 = Worksheets("Sheet1")
For i = 2 To ws1.UsedRange.Rows.Count
Set src = ws1.Range("A2" & i & ":AG10" & i)
Set dest = ws2.Range("A2" & i & ":AG10" & i)
If Source.Cells(1, 4).Value = "complete" Then
src.Copy Destination:=dest
dest.Value = dest.Value
Next i
End If
End Sub
Here some changes to your code that might help.
Sub copier()
Dim ws1 As Worksheet, ws2 As Worksheet, src As Range, dest As Range, i As Integer
Set ws1 = Worksheets("Workload - Charge de travail")
Set ws2 = Worksheets("Sheet1")
For i = 2 To ws1.Range("A1").SpecialCells(xlLastCell).Row
' this is more reliable than the method you used (which relies ont eh workbook being saved)
' but there must be no gaps in column A.
' Your code would not work. Think about whay happens as i increases!
' ws1.Range("A2" & i & ":AG10" & i)
Set src = ws1.Range("A" & i & ":AG" & i+10 )
Set dest = ws2.Range("A" & i & ":AG" & i+10 )
If Source.Cells(1, 4).Value = "complete" Then
' what is source?
' What is this trying to do! I think you mean i+1 not 1.
' I think you mean src not source. I'm not psychic.
src.Copy Destination:=dest
dest.Value = dest.Value
End If
Next i
End Sub

VBA Dragging down formulas (in multiple rows) to last row used

I have formulas from columns O -> X and need them drag them to last row used. Below is the current code I am using:
Dim wkb As Workbook
Dim wkbFrom As Workbook
Dim wks As Worksheet
Dim rng As Range
Dim path As String, FilePart As String
Dim TheFile
Dim loc As String
Dim Lastrow As Long
Set wkb = ThisWorkbook
loc = shPivot.Range("E11").Value
path = shPivot.Range("E12").Value
FilePart = Trim(shPivot.Range("E13").Value)
TheFile = Dir(path & "*" & FilePart & ".xls")
Set wkbFrom = Workbooks.Open(loc & path & TheFile & FilePart)
Set wks = wkbFrom.Sheets("SUPPLIER_01_00028257_KIK CUSTOM")
Set rng = wks.Range("A2:N500")
'Copies range from report generated to share drive and pastes into the current week tab of open order report
rng.Copy wkb.Sheets("Current Week").Range("A4")
With ActiveSheet
Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("O4:X4").AutoFill .Range("O4:X4").Resize(Lastrow)
End With
The code Lastrow is not dragging the formulas down
You can do auto-fill like this in VBA (verified using macro recording)
Range("O1:X1").Select
Selection.AutoFill Destination:=Range("O1:X25"), Type:=xlFillDefault
Now that you have this code as a base to work with you can use any variables you like in the syntax like this:
Range("O1:X1").Select
Selection.AutoFill Destination:=Range("O1:X" & Lastrow), Type:=xlFillDefault
I used this:
Sub sum_1to10_fill()
Sheets("13").Activate
Range("EG12").Copy
Range("EG12:FT36").PasteSpecial xlPasteFormulas
End sub
...and filled up my whole label both down and right.