Assigning two ranges from separate sheets to a variable - vba

I have 3 worksheets and I am trying to assign a range to a variable on one of the sheets, based on ranges in two other different worksheets. Here is my code:
Sub Combine()
Dim range1 As Range
Dim range2 As Range
Dim ID As Range
Set range1 = Worksheets(3).Range("A2:A")
Set range2 = Worksheets(4).Range("A2:A")
Set newRng = Worksheets(6).Range(range1, range2)
End Sub
I'm getting back a
Run-time error '1004'
Any suggestions?

A range can't span multiple worksheets.
This may work, depending on what you ultimately need to do:
Set newRng = Worksheets(6).Range(range1.Address, range1.Address)
But, since these ranges have the same address in your example, I think what you want is not a Range object combining them, but some other data structure, like an array, collection, or dictionary.
NOTE Your ranges are not valid to begin with, Range("A2:A") is not valid, so you'll need to fix that. See here for reliable ways to find the "last" cell in a range. I've modified it to bring in the entire column A (except A1) but you will probably want to fine-tune that.
newRange will have to be a different data type for this to work without raising a Mismatch error, for example a Collection:
Sub Combine()
Dim coll as New Collection
Dim range1 As Range
Dim range2 As Range
Dim ID As Range
coll.Add Worksheets(3).Range("A2:A" & Rows.Count)
coll.Add Worksheets(4).Range("A2:A" & Rows.Count)
Set newRng = coll
End Sub
Or as an array of range:
Sub combine()
Dim newRange(1) As Range
Set r1 = Worksheets(3).Range("A2:A" & Rows.Count)
Set r2 = Worksheets(4).Range("A2:A" & Rows.Count)
Set newRange(0) = r1
Set newRange(1) = r2
End Sub
Using the array example above, you can then assign the values to another location, modify as needed:
Worksheets(4).Range("B1").Value = newRange(0).Value
Worksheets(4).Range("B2").Value = newRange(1).Value

Related

Fill Empty Blank Cells with value within a region horizontaly defined

I'm trying to fill blank cells in a certain region with 0. The reagion should be defined in the current workbook but in sheet2 (not the current sheet). Also the place where it is supposed to fill is between columns
BU:CQ in the current region (not all 100 000 000 lines). Just the number of lines that define the table between columns BU and CQ. I know the problem lies in defining the region... See the code below.
What is missing?
Sub FillEmptyBlankCellWithValue()
Dim cell As Range
Dim InputValue As String
On Error Resume Next
InputValue = "0"
For Each cell In ThisWorkbook.Sheets("Sheet2").Range(BU).CurrentRegion
'.Cells(Rows.Count, 2).End(xlUp).Row
If IsEmpty(cell) Then
cell.Value = InputValue
End If
Next
End Sub
I've this code that i'm positive that works! But i don't wnat selection! I want somthing that specifies the sheet and a fixed range.
Now my idea is to replace "selection" with the desired range. - In this case in particular the range should be 1 - between BU:CQ; 2 - starting at row 2; 3 - working the way down until last row (not empty = end of the table that goes from column A to DE)
Sub FillEmptyBlankCellWithValue()
Dim cell As Range
Dim InputValue As String
On Error Resume Next
For Each cell In Selection
If IsEmpty(cell) Then
cell.Value = "0"
End If
Next
End Sub'
PS: And I also need to specify the sheet, since the button that will execute the code will be in the same workbook but not in the same sheet.
Use SpecialsCells:
On Error Resume Next 'for the case the range would be all filled
With ws
Intersect(.UsedRange, .Range("BU:CQ")).SpecialCells(xlCellTypeBlanks).Value = 0
End With
On Error GoTo 0
MUCH faster than looping !
Try using cells() references, such as:
For i = cells(1,"BU").Column to cells(1,"CQ").Column
cells(1,i).value = "Moo"
Next i
In your current code you list Range(BU) which is not appropriate syntax. Note that Range() can be used for named ranges, e.g., Range("TheseCells"), but the actual cell references are written as Range("A1"), etc. For Cell(), you would use Cells(row,col).
Edit1
With if statement, with second loop:
Dim i as long, j as long, lr as long
lr = cells(rows.count,1).end(xlup).row
For i = 2 to lr 'assumes headers in row 1
For j = cells(1,"BU").Column to cells(1,"CQ").Column
If cells(i,j).value = "" then cells(i,j).value = "Moo"
Next j
Next i
First off, you should reference the worksheet you're working with using:
Set ws = Excel.Application.ThisWorkbook.Worksheets(MyWorksheetName)
Otherwise VBA is going to choose the worksheet for you, and it may or may not be the worksheet you want to work with.
And then use it to specify ranges on specific worksheets such as ws.Range or ws.Cells. This is a much better method for specifying which worksheet you're working on.
Now for your question:
I would reference the range using the following syntax:
Dim MyRange As Range
Set MyRange = ws.Range("BU:CQ")
I would iterate through the range like so:
Edit: I tested this and it works. Obviously you will want to change the range and worksheet reference; I assume you're competent enough to do this yourself. I didn't make a variable for my worksheet because another way to reference a worksheet is to use the worksheet's (Name) property in the property window, which you can set to whatever you want; this is a free, global variable.
Where I defined testWS in the properties window:
Public Sub test()
Dim MyRange As Range
Dim tblHeight As Long
Dim tblLength As Long
Dim offsetLen As Long
Dim i As Long
Dim j As Long
With testWS
'set this this to your "BU:CQ" range
Set MyRange = .Range("P:W")
'set this to "A:BU" to get the offset from A to BU
offsetLen = .Range("A:P").Columns.Count - 1
'set this to your "A" range
tblHeight = .Range("P" & .Rows.Count).End(xlUp).Row
tblLength = MyRange.Columns.Count
End With
'iterate through the number of rows
For i = 1 To tblHeight
'iterate through the number of columns
For j = 1 To tblLength
If IsEmpty(testWS.Cells(i, offsetLen + j).Value) Then
testWS.Cells(i, offsetLen + j).Value = 0
End If
Next
Next
End Sub
Before:
After (I stopped it early, so it didn't go through all the rows in the file):
If there's a better way to do this, then let me know.

VBA Object Required When Getting Row From Range

I am trying to extract a single row from a range object within a function. The range is declared as a variant, and then set to a range within my sheet. I want to be able to pick out a specific row, so I tried to call .Rows(indexfrom, indexto), but I get the error Object Required. I've tried setting compareRow instead of just declaring it, but that doesn't seem to change anything. I believe it's caused because callLogRange only exists as a reference to the range object. If this is the case, how can I use the reference to get the row from the range? Alternatively, am I just missing something that enables you to get the row?
Thank you.
Dim callLogRange As Variant
callLogRange = (Sheets("CallLog").Range("B2:L" & lastRow))
Dim compareRow As Variant
compareRow = callLogRange.Rows(thisRow, thisRow)
Dim them as Ranges and use Set:
Sub dural()
Dim callLogRange As Range, thisRow As Long, lastRow As Long
lastRow = 13
Set callLogRange = Sheets("CallLog").Range("B2:L" & lastRow)
thisRow = 5
Dim compareRow As Range
Set compareRow = callLogRange.Rows(thisRow)
MsgBox compareRow.Address(0, 0)
End Sub
EDIT#1:
the cells are in the sixth row of the worksheet which is the fifth row of the primary range
if you instantiate compareRow without the Set, you are actually creating an internal VBA array rather than a Range.
Drop the parentheses.
This:
callLogRange = (Sheets("CallLog").Range("B2:L" & lastRow))
Is evaluating Sheets("CallLog").Range("B2:L" & lastRow) as a value. Remove the parentheses and you'll be assigning a 2D array instead.
Or Set the reference and you'll be assigning a Range object reference, as in Gary's answer

generating a range from other cells excel vba

I am not sure if this can be done to start with.
i am iterating through some cells and at some point I want to define a range like this:
Set rngtmp = Range(f.Column & c.Row & ":" & g.Column & c.Row)
f and g are pointing to single cells and they are okay (I mean that they work just fine) because I am also doing some operations taking them as a reference and they work.
c is the cell that i am currently at ( since I am iterating through all the cells). The range is always empty and I don't understand why.
f.column is smaller than g.column
You can use the .Cells() property.
Dim wb As Workbook, ws As Worksheet
Dim rngTmp As Range
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
With ws
Set rngTmp = .Range(.Cells(c.Row, f.Column), .Cells(c.Row, g.Column))
End With
You cannot use integers to determine the size of a range object; you are required to use the .Cells property to be able to use integers to build a range.
Edit:
As #Scott Holtzman mentioned, you must firstly pass .Row and then .Column into .Cells (the opposite to how you have it shown in your question).
As #eirikdaude mentioned, you can use .Range and then use the .Resize property; this allows you to use integers with the range, instead of having to use the .Cells property. This is an approach which I typically use when writing arrays to a worksheet.
Use Cells to refer to a single cell. You can then join these in a range:
Sub Test()
Dim rngtmp As Range
Dim f As Range
Dim c As Range
Dim g As Range
With ThisWorkbook.Worksheets("Sheet1")
Set f = .Range("A1")
Set c = .Range("D8")
Set g = .Range("L22")
Set rngtmp = .Range(.Cells(c.Row, f.Column), .Cells(g.Column, c.Row))
End With
End Sub
Note that .Range and .Cells will refer to Sheet1 due to the With...End With block.
https://msdn.microsoft.com/en-us/library/wc500chb.aspx
You can't use .Column as it returns the integer index of the column, not a letter.
Try something along the lines of
set rngtmp = Range(Cells(f.Row, c.Column), Cells(g.Row, c.Column))
of course you will need to reference sheets and cells and such as required

Passing range objects to functions in excel-vba -- receive "Object Required" error

I'm trying to build a function that will take an input cell (say "B5") and return a range object that refers to a table (of which the supplied cell is the top-right entry)
Sub Macro1()
Dim testCell As Range
testCell = Worksheets("HMA").Range("B5")
ReturnTable testCell
End Sub
Function ReturnTable(cell As Range)
firstcell = cell
lastrow = firstcell.End(x1Down)
Table = Range(firstcell, lastrow + 5).Value
End Function
I've been running into a lot of problems here, and I feel like I'm missing something simple. The error that I'm getting is "Object Required" at the lastRow line.
Looking through it in debug mode I see that testCell is assigned the value of the range object (I assume this is the default). What am I missing here?
Is my approach even sound? Should I be looking at solving this problem in a different way?
The End returns a Range object, so, lastrow must be a range variable.
Function ReturnTable(firstcell as Range) as Range 'add this as range to tell the result of the function is a range
dim LastCell as Range
Set LastCell = firstcell.END(xldown)
Set ReturnTable = Range(firstcell, lastcell) 'must use the same name of the function
End Function
If you want 5 cells below lastcell, use LastCell.Offset(5,0)
And in Macro1, you probably will want something like
Set SomeVar = ReturnTable(testcell)
When you assign Objects (like Range) you have to use "Set".
If you assign Range without "Set" VBA will assign the value of the Range and not the Range itself.
Set testCell = Worksheets("HMA").Range("B5")

VBA: adding distinct values in a range to a new range

I have an unsorted list of names in Sheet1, Column A. Many of these names appear more than once in the list.
On Sheet2 Column A I want an alphabetically sorted list of the names with no duplicate values.
What is the optimal method of achieving this using VBA?
Methods I have seen so far include:
Making a collection with CStr(name) as the key, looping through the range and trying to add each name; if there is an error it is not unique, ignore it, else expand the range by 1 cell and add the name
Same as (1), except ignore about the errors. When the loop is complete, only unique values will be in the collection: THEN add the whole collection to the range
Using the match worksheet function on the range: if no match, expand the range by one cell and add the name
Maybe some simulation of the "remove duplicates" button on the data tab? (haven't looked into this)
I really like the dictionary object in VBA. It's not natively available but it's very capable. You need to add a reference to Microsoft Scripting Runtime then you can do something like this:
Dim dic As Dictionary
Set dic = New Dictionary
Dim srcRng As Range
Dim lastRow As Integer
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
lastRow = ws.Cells(1, 1).End(xlDown).Row
Set srcRng = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, 1))
Dim cell As Range
For Each cell In srcRng
If Not dic.Exists(cell.Value) Then
dic.Add cell.Value, cell.Value 'key, value
End If
Next cell
Set ws = Sheets("Sheet2")
Dim destRow As Integer
destRow = 1
Dim entry As Variant
'the Transpose function is essential otherwise the first key is repeated in the vertically oriented range
ws.Range(ws.Cells(destRow, 1), ws.Cells(dic.Count, 1)) = Application.Transpose(dic.Items)
As you suggested, a dictionary of some sort is the key. I would use a Collection - it is builtin (in contrary to Scripting.Dictionary) and does the job.
If by "optimal" you mean "fast", the second trick is to not access each cell individually. Instead use a buffer. The below code will be fast even with thousands of rows of input.
Code:
' src is the range to scan. It must be a single rectangular range (no multiselect).
' dst gives the offset where to paste. Should be a single cell.
' Pasted values will have shape N rows x 1 column, with unknown N.
' src and dst can be in different Worksheets or Workbooks.
Public Sub unique(src As Range, dst As Range)
Dim cl As Collection
Dim buf_in() As Variant
Dim buf_out() As Variant
Dim val As Variant
Dim i As Long
' It is good practice to catch special cases.
If src.Cells.Count = 1 Then
dst.Value = src.Value ' ...which is not an array for a single cell
Exit Sub
End If
' read all values at once
buf_in = src.Value
Set cl = New Collection
' Skip all already-present or invalid values
On Error Resume Next
For Each val In buf_in
cl.Add val, CStr(val)
Next
On Error GoTo 0
' transfer into output buffer
ReDim buf_out(1 To cl.Count, 1 To 1)
For i = 1 To cl.Count
buf_out(i, 1) = cl(i)
Next
' write all values at once
dst.Resize(cl.Count, 1).Value = buf_out
End Sub