Setting up a dynamic range in excel-vba - vba

I'm basing my code off of this.
Excel VBA - select a dynamic cell range
I'm trying to find the syntax to create a dynamic range. Example: I always start on D8 but the upper bound of the range is based on an int count in another cell. [h4]
Dim count As Integer
count = Sheet2.Cells(8,1).Value
Set refRng = Sheet2.Range("D8:" & Cells(8, i).Address)
Is the relevant code sample.
I now know that Sheet2.Range("H1") doesn't return an int, it returns a variant or something?
I've tried a million different things and have figured out that none of them work. There has to be a better way to set up a dynamic range.

Not 100% sure what you're trying to achieve but in terms of messing around with ranges maybe this is a start:
Option Explicit
Sub select_Range()
Dim count As Integer
count = ThisWorkbook.Worksheets("Sheet2").Range("A8").Value
Dim i As Integer
i = count
Dim refRng As Excel.Range
Set refRng = ThisWorkbook.Worksheets("Sheet2").Range("D8:D" & i)
refRng.Select
End Sub
This results in the following on Sheet2:

This was originally a comment, but it is also the solution so I am adding it as an answer
Cells(8, 1) = "A8". If you want cell H1 it would be Cells(1, 8) or Cells(1, "H"). If you want cell H4 it would be Cells(4, 8) or Cells(4, "H").
Alternately, just Range("H1") or Range("H4")

Related

Copy specific cell to another worksheet

This has been driving me crazy and is something that should be easy, but I never touched vba before, so...
I have a for loop iterating on a row searching for matching occurrences, I know the loop is working because I can get an accurate count of the number of matching occurrences. Essentially "if month = month then counter=counter+1"
Whenever the loop finds a matching occurrence I need it to copy a specific cell (let's say AA22) to another worksheet, but I cant get it to work, it keeps throwing error codes with super broad and vague descriptions. I've tried a few of the solutions here and a few on other forums, nothing works correctly. Also, it seems every solution works with ranges, I need one that copies cells one by one.
Here's my code:
Dim chomonth As Integer
chomonth = InputBox("Insira o mes ", "Inserir dados")
Dim counter As Integer
Dim rng As Range
Dim rw As Range
Dim cell As Range
Set rng = Range("S3:S9999")
For Each rw In rng.Rows
If month(rw.row) = chomonth Then
//Code that copies AArw to worksheet 2 goes here
counter = counter + 1
End If
Next rw
MsgBox ("Numero de entradas:" & Count)
Try this:
If month(rw.row) = chomonth Then
counter = counter + 1
Worksheets("Sheet2").Cells(counter, 1).Value = Worksheets("Sheet1").Cells(rw.row, 27).Value
End If

How to use column/row index as range in VBA

Like using Cells(1, 1) instead of Range("A1"), what's the best way to use column/Row index as range in VBA?
I came up with 2 solutions to denote Range("A:A"):
Range(Cells(1, 1), Cells(Columns(1).Rows.count, 1))
Union(Columns(1), Columns(1))
Is there a better and more concise solution?
Edit: noted response from Tehscript and thanks for the same. I already tried that but it's giving below error:
Run-time error '13': Type mismatch.
Here's the code:
Sub tfind()
Dim r1 As Range
Set r1 = Columns(1)
MsgBox mCount("Test:", r1)
End Sub
Function mCount(find As String, lookin As Range) As Long
Dim cell As Range
For Each cell In lookin
If (Left(cell.Value, Len(find)) = find) Then mCount = mCount + 1
Next
End Function
Although it works fine if the 3rd line:
Set r1 = Columns(1)
is changed to:
Set r1 = Union(Columns(1), Columns(1))
There is no best way to do this, but there are ways that you can use according to your needs. For example if you want to loop through both rows and columns you should better use Cells():
Sub RowTimesColumn()
Dim i As Long, j As Long
For i = 1 To 10
For j = 1 To 5
Cells(i, j) = i * j
Next j
Next i
End Sub
On the other hand you can reference a range like Range("A1:B3") in either way depending on your needs. If you simply need the reference, you should use Range("A1:B3"). If you need to play with the rows and columns, you should better use Range(Cells(1, 1), Cells(3, 2)).
It is all about readability and functionality.
For your question, you might want to use the following:
Range("A:A") --> Columns(1)
Range("A:C") --> Range(Columns(1), Columns(3))
Edit: You are looping through the cells within Column A, in that case you need to use:
Columns("A").Cells or Columns(1).Cells

Setting variables VBA

complete novice here
I started some VBA a few days ago, I have simple question but cant seem to find what I am doing wrong.
I am trying to make a button which will take the coordinates of the active cell and compare them to another worksheet to retrieve a specific value from another table.
I set variables to the active cell column and row, I want to do this so I can later compare these locations to another worksheet and get the value at a specified position on another worksheet.
So far I have written simply what I could find on the internet as I have no formal training.
The msgbox at the end is just to test whether or not it actually picks up the reference.
Sub CommandButton1_Click()
Dim Arow As Range
Dim Acol As Range
Set Arow = Worksheets("Sheet1").Range(ActiveCell.Row)
Set Acol = Worksheets("Sheet1").Range(ActiveCell.Column)
MsgBox (Arow)
End Sub
So far I have error run-time error '1004' Application defined or object defined error highlighting the 4th Row. If anyone could help me solve this or redirect me to some help it would be much appreciated.
I think this won't work, you should put there
Set arow = Worksheets("Sheet1").Range(ActiveCell.Row & ":" & ActiveCell.Row)
Putting there simply number won't work. For the column, you should put there somethong like C:C. For getting letter of column, see this qestion: Function to convert column number to letter?
For more information about Range property, please see official documentation https://msdn.microsoft.com/en-us/library/office/ff836512.aspx.
The thing is, that you have to supply either the address in so called A1 reference, which is "A1", or "$A$1" or name of cell, etc, or you have to supply two Range objects, such as two cells Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(1,1), Worksheets("Sheet1").Cells(2,2)), which defines area starting with upper-left corner in first parameter and lower right in second parameter.
ActiveCell.Row and ActiveCell.Column returns you some Integer value representing number of row and column, i.e. if you point cell B4, ActiveCell.Row would return 4, and ActiveCell.Column gonna return 2. An Range() property need as an argument whole adress for some range, i.e. Range("C6") or Range("G3:J8").
When you have your column as a number, you can use Cells() property for pointing first and last cell in your range, i.e. Range(Cells(2, 4), Cells(6, 8) would be the same range as Range("D2:H6").
Following this, one of the ways that you can do what you have described is:
Sub CommandButton1_Click()
Dim Rng As Range
Set Rng = Worksheets("Sheet1").Cells(ActiveCell.Row, ActiveCell.Column)
End Sub
Now you have under variable Rng an Range of the same coordinates as ActiveCell, but in Sheet1. You can pass some value into i.e Rng.Value = "Hello World", paste something with Rng.PasteSpecial xlPasteAll etc.
if you want the value from other sheet at the same location as activeCell, use this code,
Private Sub CommandButton1_Click()
valueFromOtherSheet = Sheets("Sheet2").Range(ActiveCell.Address)
MsgBox (valueFromOtherSheet)
End Sub
Like the others have said, it's just about knowing your variable types. This is another way you could achieve what you want
Sub CommandButton1_Click()
Dim Acell As Range
Set Acell = Worksheets("Sheet2").Range(ActiveCell.Address)
MsgBox "Value on ActiveSheet: " & ActiveCell.Value & vbNewLine & _
"Value on Sheet2: " & Acell.Value
End Sub
Thank you everyone for the help and clarification, In the end I was able to come up with some code that seems to do what I need it to.
Private Sub CommandButton1_Click()
Dim cabDate As Range
Dim searchCol As Integer
Dim newindex As Range
Set cabDate = WorksheetFunction.Index(Range("A1:O9999"), ActiveCell.Row, 2)
searchCol = ActiveCell.Column
Set newindex = WorksheetFunction.Index(Worksheets("Deadlines").Range("A1:O9999"), cabDate.Row, searchCol)
MsgBox (newindex)
End Sub
I wasn't aware about conflicting data types so thank you all for the assistance.

Set a range to an entire column with index number

I'm building a function that takes a column number as an input to return the highest value in the column.
I need to work with an entire column with a column index number. The following code works but I need an index number instead of using "B:B" to reference the column.
Set rng = Range("B:B")
When I use the following code, everything seems to break down. It always returns a 0 even though the highest number is 44. Can you see what I am doing wrong? It worked perfectly when I used "B:B" as a range.
Set rng = Range(Columns(2),Columns(2))
It doesn't seem to recognize anything in the range. Any help would be awesome!
Try this
Sub Sample()
Dim Rng As Range
'~~> This will let you work with Col B
Set Rng = Columns(2)
'~~> This will give you the Max in that column
MsgBox Application.WorksheetFunction.Max(Rng)
End Sub
This is from a solution I found a while back:
Dim x, y As Int
Dim rng As Range
x = 1 ' For A
y = 4 ' For D
Set rng = Columns(Chr(64 + x) & ":" & Chr(64 + y))
Source: http://www.mrexcel.com/forum/excel-questions/114025-visual-basic-applications-select-multiple-columns-using-column-number.html

EXCEL-VBA Change a range with a loop

Set rng = Worksheets("Sheet1").Range("B2")
I have the above and would like to run a loop that changes the range I use/evaluate. I have tried variations of the following.
for x = 2 to 10
Set rng = Worksheets("No-Funding").Range(x & "2")
Next X
I have done some investigating and found this other Stack Overflow: Excel VBA Looping formula to change Range I can not make sense of it in this situation though.
My code will not work if it uses cells either, I have tried that and can only make it work with Range. Thanks for any help provided!
For a strictly numerical increment try,
Set rng = Worksheets("No-Funding").Cells(x, 2)
An xlA1 style reference can be achieved by factoring in the ASCII character.
Set rng = Worksheets("No-Funding").Range(Chr(64 + x) & 2)
Try this:
For x = 2 To 10
Set rng = Worksheets("No-Funding").Cells(2, x)
Next x
As far as I know it is no matter for VBA if you use function .Range or .Cells, since both of them return object or Range type.
Use
Set rng = Worksheets("Sheet1").Range("B2").Offset(0,x)
to move to a different column. Better yet
Dim values as Variant, rng as Range
Set rng = Worksheets("Sheet1").Range("B2").Resize(10,1)
values = rng.Values2
For i=1 to 10
values(i,1) = 2*values(i,1)
Next i
rng.Values2 = values