.Rows() will not accept a string value - vba

I'm writing a routine to insert some rows, and to copy over some values.
The amount and position of the rows that need to be inserted are dynamic and stored in variables.
I know I can insert rows by using Activesheet.rows("2:12").Insert shift:=xlDown
Now as the 2 and 12 are dynamic I declared variables of datatype Long to hold those values. For example:
Dim Startvalue as Long
Startvalue = 2
Dim Lengthofinsert as Long
Lengthofinsert = 10
Dim Endvalue as Long
Endvalue = Startvalue + Lengthofinsert
Then I wrote the following: Activesheet.rows("""" & Startvalue & ":" & Endvalue & """").Insert shift:=xlDown which results in a type mismatch.
Using debug.print("""" & Startvalue & ":" & Endvalue & """") the result of this is "2:12", exactly the same as I entered in my first insert() statement above.
I thought perhaps first storing the string as a string variable might help, but that unfortunately also results in the same type mismatch.
Now I figure rows should take some sort of Array or Range as argument, but how do I convert my two Long's into that?

just use
ActiveSheet.Rows(Startvalue & ":" & Endvalue).Insert shift:=xlDown
You don't need the "" because Startvalue & ":" & Endvalue is already a string (the long values automatically cast into a string due to the concatenation with &).
Same like
Dim MyRows As String
MyRows = Startvalue & ":" & Endvalue
ActiveSheet.Rows(MyRows).Insert shift:=xlDown
Or as #Chronocidal pointed out in the comment:
Compare the outputs
Debug.print("""" & Startvalue & ":" & Endvalue & """") 'output: "2:12"
Debug.Print("2:12") 'output: 2:12

Have you created Thisworksheet? It's not mentioned in your declarations.
Assuming you have,
Try
ThisWorkSheet.rows(Startvalue & ":" & Endvalue).Insert shift:=xlDown
Otherwise try:
Activesheet.rows(Startvalue & ":" & Endvalue).Insert shift:=xlDown

Related

Automated tool for VLOOK UP

I need to perform many VLookup in a set of excel files, and for that I built a tool that can make automated VLookup from a file to another but I need to be make it scalable and adaptable.
For that, I want to input in some cells of the tool (which is an Excel file) the parameters for the VLookup:
Position of Key Column
Position of "Returned Value" Column
Number of Columns in the range
Do you know how to change my tool in order for it to include these entry parameters ?
a sample of the code here:
For myrow = 3 To lastrow
Range("b" & myrow).FormulaR1C1 = _
"=VLOOKUP(RC[-1], Input!C[-1]:C[2],2,FALSE)"
Next myrow
I'm not well versed in R1C1 notation, but if you were using regular .Formula notation:
The following code assumes that A1 = Key column, A2 = Returned value column, A3 = Number of columns in the range (which is really just your return column).
lastrow = 10 just for the example
Also note - you must be missing a field... since you should have 4 variables - key column for first parameter, 2 column letters for second parameter, and the number of columns for 3rd parameter.
Sub Test()
lastrow = 10
For myrow = 3 To lastrow
'Range("B" & myrow).Formula = "=VLOOKUP(" & Range("A1").Value & myrow & ",Input!$" & Range("A1").Value & ":$" & Range("A2").Value & "," & Range("A3").Value & ",FALSE)"
Debug.Print "=VLOOKUP(" & Range("A1").Value & myrow & ",Input!$" & Range("A1").Value & ":$" & Range("A2").Value & "," & Range("A3").Value & ",FALSE)"
Next myrow
End Sub
Values on ActiveSheet:
Immediate window returns:

Type Mismatch when passing an integer result to an integer type variable

Dim codeStart As String
codeStart = Evaluate("CELL(""address"",OFFSET(" & startRange & ",2,0,1,1))")
Dim agentTotal As String
agentTotal = Evaluate("CELL(""address"",INDEX(" & startRange & ":" & _
"$A$10000,MATCH("" Total*""," & startRange & ":$A$10000,0)))")
Dim numberOfCodes As String
numberOfCodes = Evaluate("ROW(" & agentTotal & ")-ROW(" & codeStart & ")")
MsgBox numberOfCodes
The first two variables properly pass as strings when tested with a Msgbox
I've tried setting numberOfCodes to a few different variable types and putting CInt in front of Evaluate but no dice..any ideas?
When you perform the following statement
Evaluate("ROW(" & agentTotal & ")-ROW(" & codeStart & ")")
it returns a Variant (which is what Evaluate will always return) but, because you are using ROW (which can return an array), it will either return a Variant/Variant(1 To 1) (if only a single row is being returned) or a Variant/Variant(1 To x, 1 To 1) (if x rows are being returned).
Normally a Variant can be cast to a String or an Integer (if the value permits) but, because in this case it is a Variant array, it can't be converted to a single value.
In your case, the following code would have worked:
Dim numberOfCodes As Variant
numberOfCodes = Evaluate("ROW(" & agentTotal & ")-ROW(" & codeStart & ")")
MsgBox numberOfCodes(1)
or
Dim numberOfCodes As Integer
numberOfCodes = Evaluate("ROW(" & agentTotal & ")-ROW(" & codeStart & ")")(1)
MsgBox numberOfCodes
but another way would have been to simply say:
Dim numberOfCodes As Long
numberOfCodes = Range(agentTotal).Row - Range(codeStart).Row
But that simplification could have gone back a lot further. For instance you are using the code Evaluate("CELL(""address"",OFFSET(" & startRange & ",2,0,1,1))") to find an address, but you are really after the row number, so you could leave out that and calculate numberOfCodes as
numberOfCodes = Range(agentTotal).Row - Range(startRange).Row - 2
And you can also get rid of AgentTotal by using
numberOfCodes = Application.Match(" Total*", _
Range(startRange, "$A$10000"),0) - 3
which just calculates the number of rows (inclusive) from startRange to the "Total" and subtracts 3 (to exclude the two headers(?) and the total).
I'm just going to take these evaluates and and tack on .Row and pass them to integers and just subtract agentTotalRow from codeStartRow. Works perfectly now.

SUMIFS function from other workbook - Error is Type Mismatch

I would like to do SUMIFS function in a range of active sheet from other workbook. Here is where I get my error of Macro:
ActiveSheet.Range(ActiveSheet.Cells(6, lastCol + 1),
ActiveSheet.Cells(lastRow, lastCol + 1)).Formula = Application.WorksheetFunction.SumIfs(" ' " & wbGSD.Name & "'!$F$10:$F$" & wbGSDlastRow & ",'" & wbGSD.Name & "'!$B$10:$B$" & wbGSDlastRow & ",B6,'" & wbGSD.Name & "'!$C$10:$C$" & wbGSDlastRow & ", Total")
The error I got is:
Type Mismatch
I tried Sumif function. It didn't work either.
You're passing SumIfs() one long string. It doesn't take one long string. It takes a number of parameters, the first two of which are Range objects, not strings. If you want to write your formula as one long string, then there's no need for WorksheetFunction.SumIfs(). Just assign the string formula to the range's Formula property:
Range("A1").Formula = "=SUMIFS('" & wbGSD.Name & "'!$F$10:$F$" & ...
If you really do want to use WorksheetFunction.SumIfs(), you'll need to use it properly by passing individual parameters of the right type:
Range("A1") = WorksheetFunction.SumIfs( _
Sheets(wbGSD.Name).Range("$F$10:$F$" & wbGSDlastRow), _
Sheets(wbGSD.Name).Range("$B$10:$B$" & wbGSDlastRow), _
....

VBA - get range using Dim values - range of object __global failed

I have the following Dims
Dim PlayersStartAt As Integer
Dim PlayersEndAt As Integer
PlayersStartAt = 101
PlayersEndAt = PlayersStartAt + 50
Selection.AutoFill Destination:=Range("B & PlayersStartAt:B & PlayersEndAt"), Type:=xlFillDefault
and want to execute the following line of code.
It with great with Range("B101:B151");
What is wrong with my syntax?
Change this
Range("B & PlayersStartAt:B & PlayersEndAt")
to
Range("B" & PlayersStartAt & ":B" & PlayersEndAt)
PlayersStartAt and PlayersEndAt are variables. Anything that you put between quotes will be taken as a string :)

SUM formula VBA

I am trying to calculate the sum of changing cell range in vba. Unfortunately the cell values are variables. I can't seem to get the following formula to work.
Private Sub calcOverheadRate(startCell As Integer, endCell As Integer)
Total = endCell + 1
Range("D" & Total).Formula = "=SUM("D" & startCell & ":" & "D" & endCell)"
End Sub
I get compile error: "Expected: end of statement
To solve this problem I changed the function to,
Private Sub calcOverheadRate(startCell As Integer, endCell As Integer)
Dim start As String
Dim endC As String
start = "D" & CStr(startCell)
endC = "D" & CStr(endCell)
Total = endCell + 1
Range("D" & Total).Formula = "=SUM(start:endC)"
End Sub
The function compiles fine, when I run it, the value in the cell is "#NAME" where it references SUM(start:endC) not SUM(D5:D23)....
Any thoughts on how to solve this would be appreciated.
The quotes are the issue:
Range("D" & Total).Formula = "=SUM(" & startCell & ":" & endCell & ")"
I have figured out the problem the & needs to be inside the quotation for string literals
Range("D" & Total).Formula = "=SUM(" & start & ":" & endC & ")"
How about you try using a table?
Here is a 1 min video on how to make a table in Excel:
http://www.screenr.com/VvZ8