Using a variable in a range statement in VBA excell macro - vba

Ok, I'm sure this question is really basic but all my searchers turn up complicated answers and I've been messing with VBA for about a day. I have two worksheets in an excel doc, I've created a button that I can click that invokes my macro that is just moving cells from one work sheet to another. But I need my macro to determine what row I am on. I'm using this:
r = ActiveCell.Row
to determine my row, but what would be the easiest way to use that variable in a range statement like this:
Range("A2").Select

You could use the Range method with the & operator to join the variable into a string:
Range("A" & r)
Alternately you can use the Cells method which takes arguments (Row, Column):
Cells(r, "A")

Related

GoalSeek only within VBA, without depending on a WorkSheet Cell

Very shortly: Instead of ActiveCell of ActiveCell.GoalSeek Goal:=0, ChangingCell:=Range("GM")formula, how can I use a variable? So I want to use something like GoalSickVariable.GoalSeek Goal:=0, ChangingCell:=Range("GM")
.
As a detail:
I am trying to shorten my current GoalSeek formulation and I'm stucked on the last line.
So far, I was running my codes within WorkSheet but as I can't assume which part of the Worksheet will be empty, I was going to a cell which is away from the reference cell by .Offset(0,25) but as user can also use that cell, I would like not to use any range within WorkSheet - if it's possible.
...
ActiveCell.Offset(0, 25).Select
ActiveCell.Formula = "=ROUNDUP(SellPrice,-3)"
RoundedCellAddress = ActiveCell.Address
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=(" & RoundedCellAddress & "-" & "SellPrice" & ")"
'SellPrice is a NamedRange from this current Worksheet
ActiveCell.GoalSeek Goal:=0, ChangingCell:=Range("GM")
'GM is also a NamedRange from this WS and it changes SellPrice's value.
...
While it's a very bad practice with many ActiveCell and a Assuming Cell Reference, this above code is working without any problem. Anyway as I explained above, I don't want to assume this .Offset(0,25) cell and don't want to use these ActiveCells.
So here below how I transformed my code into a good practice:
...
RoundedSellPrice = Application.WorksheetFunction.RoundUp(ws4.Range("SellPrice"), -3)
GoalSick = RoundedSellPrice - ws4.Range("SellPrice")
GoalSick.GoalSeek Goal:=0, ChangingCell:=ws4.Range("GM")
...
But now as you can easily guess, it gives me Invalid Qualifier error on GoalSick.GoalSeek line because GM and SellPrice are variables defined within WorkSheet so they are (I think) not able to run GoalSeek formula from VBA module without exactly referring to any cell(contains formula) within the WorkSheet.
If somehow I can not do this formulation without referring to a cell within the WorkSheet, how should I suppose to do without assuming a dummy cell like .Offset(50,150) or without creating a new empty WorkSheet?

Excel use cell value as range in VBA

I have an excel file. There is a changable row quantity for column A for every time and that's why I need to make dynamic formula. For example;
I want to write "=LEN(B1)" formula on B1. And when make double click on right down corner of the cell, it's going to the end of until when column A values ends. That's why, before all this process, I wrote "=COUNT(A:A)" on cell C1.
In my VBA, I want to write;
Dim TEMP As String
TEMP = Range("C1").Value
Range("B1").Select
ActiveCell.FormulaR1C1="=+LEN(RC[-1])"
Selection.AutoFill Destination:=Range("B1:TEMP")
But there is something wrong in this process. As a result, I just want to use a cell value in my VBA as a range or string or number.
Thanks for your support.
Two notes:
It's best practice to always qualify your objects (workbooks, worksheets, ranges, etc.) beforehand
When you use R1C1 notation, you can just write the formula directly to the range (with no need for AutoFill or FillDown)
Try this:
Dim ws as Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") 'edit for your sheet name
Dim lRow as Long
lRow = ws.Range("A" & ws.Rows.count).End(xlup).Row
ws.Range("B1:B" & lRow).FormulaR1C1 = "=Len(RC[-1])"
And just as a side note worth mentioning the way you wrote Range("B1:TEMP") is not proper syntax. Correct syntax would be Range("B1:B" & TEMP), which, of course, would only work if TEMP was indeed a numerical value :)

VBA to assign a cell content as a formula not its results

I'm trying to assign a cell a formula using VBA, but every time I run the code it assign to the cell the result not the formula itself, like when I enter the formula using the excel spreadsheet.
Does anyone know how to display the formula using a macro within a cell and not the formula result.
I'm asking this because I need to insert this line within an existing sheet among other data and then run another macro to keep it updated, and the macro depends on this formula.
The code I'm using
Cells(C, 9).Formula = Application.Index(Plan2.Range("B2:D10000"), _
Application.Match(Plan1.Range("B" & C) & Range("F" & C), Plan2.Range("A2:A10000"), 0), 3)
As you can see this formula depends on the row that its inserted.
Your Formula is ultimately being reduced to whatever is returned by Application.Index. Unless the value being returned there is an actual formula string then you will just get a number as the result and this is set to the .Formula.
If you want to actually set the formula, you need to create a string in VBA that represents the formula to use. In this case, that string would look something like:
Cells(C, 9).Formula = "=INDEX(Plan2!B2:D10000, MATCH(Plan1!B" & C & "..."
where you concatenate in the dynamic parts. The end result needs to look like a normal formula. The Application.XXX and Application.WorksheetFunction.XXX functions return actual results, not pieces that can be combined to create a formula.

How to move to next blank cell?

I have data on multiple sheets in a workbook that I want copied all to one sheet in that same workbook. When I run the macro, I would like it to start by deleting the current data in the "iPage Data Export" sheet and then replacing it with data from the other sheets.
I want the process to occur one column at a time since I may not bring over everything. Right now I am trying to learn how to do just one column.
I was able to get it to copy all of the contents of a column from one sheet, but when it moves to the next sheet, it overwrites the existing data. In the end, I only get one sheets worth of data copied.
Here are my 4 problems:
How do I make it clear the data on this sheet before running the routine?
How can I make it start each copy function at the bottom of that row (i.e. after the last cell with a value)? I have tried many of the suggestions on this and other boards without success. I will admit I am not very experienced in this.
How can I make it copy to a particular column (currently it just seems to default to A.
How can I concatenate multiple columns during the paste function? I.e. what if I want it to insert: A2&", "B2 instead of just A2
Sub CombineData()
Dim Sht As Worksheet
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name <> "iPage Data Export" Then
Sht.Select
Range("C:C").Copy
Sheets("iPage Data Export").Select
ActiveSheet.Paste
Else
End If
Next Sht
End Sub
How do I make it clear the data on this sheet before running the routine?
Sht.Cells.ClearContents
How can I make it start each copy function at the bottom of that row (i.e. after the last cell with a value)? I have tried many of the suggestions on this and other boards without success. I will admit I am not very experienced in this.
Range("C" & Rows.Count).End(xlUp).Offset(1, 0)
In detail:
Rows.Count will return the number of rows in the sheet, so in the legacy style *.xls workbooks this would return the number 65,536. Therefore "C" & Rows.Count is the same as C65536
Range("C" & Rows.Count).End(xlUp) is the same as going to C65536 and pressing Ctrl + ↑ - The command End(xlDirection) tells the program to go the last cell in that range. In this case, we would end up at the last cell containing data in column C.
.Offset(1, 0) means that we want to return the range offset by an amount of rows and/or columns. VBA uses RC (Rows Columns) references, so whenever you see something like the Offset() function with two numbers being passed as the arguments, it usually relates to the row, and the column, in that order. In this case, we want the cell that is one row below the last cell we referenced.
All-in-all the phrase Range("C" & Rows.Count).End(xlUp).Offset(1, 0) means go to the last cell in column C, go up until we hit the last cell with data, and then return the cell below that - which will be the next empty cell.
How can I make it copy to a particular column (currently it just seems to default to A.
Range("C:C").Copy Destination:=Sheets("iPage Data Export").Range("A:A")
You can pass the Destination argument in the same line and actually bypass the clipboard (faster and cleaner)
How can I concatenate multiple columns during the paste function? I.e. what if I want it to insert: A2&", "B2 instead of just A2
Lets say you wanted to reference column A, B, and F - just use:
Range("A1, B1, F1").EntireColumn
To summarise, you could streamline your existing code to something like (untested):
Sub CombineData()
Dim Sht As Worksheet
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name <> "iPage Data Export" Then
Sht.Range("C1:C" & Cells(Sht.Rows.Count, 3).End(xlUp).Row).Copy Destination:=Sheets("iPage Data Export").Range("A:A")
End If
Next
End Sub
This should do for the copying:
Sub CombineData()
Dim sheet As Worksheet
For Each sheet In Worksheets
If (sheet.Name <> "iPage Data Export") Then
sheet.Select
Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Worksheets("iPage Data Export").Activate
Cells(1, ActiveCell.SpecialCells(xlCellTypeLastCell).Column + 1).Select
ActiveSheet.Paste
End If
Next
End Sub
For the concatenation you need to be more specific - but I guess you should open a new question with a clearer focus if you need specific help on that.

Writing formula into an Excel Range with Option Strict On

Is it possible to write formulas across a range in Excel from VB.Net? I'm using a String array to hold a list of formulas that I would like to apply to an Excel range, instead of looping through and writing them one at a time.
This line is what I am attempting to use to write to a range:
xlWorkSheet.Range("AF" & intCurrentRow.ToString & ":AG" & intCurrentRow.ToString).Formula = formulas
The formula is being written to Excel, but Excel is actually displaying the formula, instead of the calculated value. If I write each formula to each cell like this:
xlWorkSheet.Range("AF" & intCurrentRow.ToString).Formula = formulas(0)
xlWorkSheet.Range("AG" & intCurrentRow.ToString).Formula = formulas(1)
It works perfectly fine and Excel displays the calculated values as it should. Almost seems like I'm missing a step but I haven't been able to find anything in my research.
As soon as I hit post I figured out the problem. Instead of using the .Formula property of an Excel.Range, you have to use the .FormulaArray property instead.
xlWorkSheet.Range("AF" & intCurrentRow.ToString & ":AG" & intCurrentRow.ToString).FormulaArray = formulas