VBScipt to Excel - Range Function Syntax - excel

re: Excel 2007
I'm using VBScript to create an Excel file and have a small issue with Syntax i think...
If i do this it happily pastes my chart from my application to a sheet in Excel at cell A1:-
ActiveDocument.GetSheetObject("CH_Contacts").CopyTableToClipboard True
XLSheet2.Paste XLSheet2.Range("A1")
What i now need to do is substitute variables instead of A1 but i'm unsure of the correct syntax to do this.
I have 2 variables called num_cols & num_rows so i want to do something like...
XLSheet2.Paste XLSheet2.Range(num_cols,num_rows)
I notice if i record an Excel macro and drag an area it produces this sort of thing...
Range("PV58:PZ58").Select
So do i need quotes somewhere as well ? Do i need the colon in there too with variables?
Any help appreciated

Assuming num_cols and num_rows are Long/Integer data type representing the column/row number (i.e., Column A == 1, Row 16 == 16, etc.), then use the Cells property:
XLSheet2.Paste XLSheet2.Cells(num_rows, num_cols)
The Cells property returns the range at the specified index of row number/column number, so:
Cells(1,1) '## Range("A1") -- Row 1, Column 1
Cells(13, 5) '## Range("E13") -- Row 13, column 5
Etc.
So do i need quotes somewhere as well ? Do i need the colon in there too with variables?
No, only if you are trying to build a literal address string, like "A6:A13", and even then it's not strictly necessary and the range can usually be constructed with another method like Resize or Offset.

Related

Excel VBA: Using 2 variables with Match

ws2.Range("D3").Value = Application.WorksheetFunction.Match(variable_i, ws2.Range("A:A"), 0)
ws1 = worksheet 1
ws2 = worksheet 2
On ws1 I have 2 columns of drop down boxes (data validation list)
the selection from the first column of drop down boxes is assigned to the variable "variable_i"
the selection from the second column of drop down boxes is assigned to the variable "variable_p"
It pulls its data from ws2 (the range is all of column a)
It is looking for the selection from the drop down box with the variable "variable_i"... the code works fine, it returns the number row on D3 without any issues
I'm looking for it to return the row number that contains both variables in the 2 columns (variable_i and variable_p)
I've tried the following code:
ws2.Range("D3").Value = Application.WorksheetFunction.Match(variable_i & variable_p, ws2.Range("A:B"), 0)
as I had seen that online, but it doesn't work for me.
The error I get is:
"Run-time error '1004':
Method 'Match' of object 'WorksheetFunction' failed
What would be the best way to have multiple variables be the lookup?
Any help would be much appreciated!
The key for you I believe could be to use EVALUATE() function. Multiple criteria would mean you most likely need an array which EVALUATE will recognize. Also concatenating values and ranges to check for two criteria is definately not the best solution. Imagine cell A1=1 and B1=101. What happens if you concatenate ranges to 1101 and you look for criteria1 10 and 11 instead of 1 and 101?
A simple evaluate example:
Debug.Print Evaluate("MATCH(1,(A1:A6=1)*(B1:B6=""B""),0)")
In my example I have one Long and one String variable, respectively 1 and B. Would I use your named variable variable_i and variable_p I could make a code like:
ws2.Range("D3") = Evaluate("MATCH(1,('Sheet1'!A1:A6=" & variable_i & ")*('Sheet1'!B1:B6=""" & variable_p & """),0)")
Notice the difference of adding a Long or a String variable? That's because to evaluate correctly in VBA there needs to be two quotation marks surrounding a String variable. A number can do without.
Also notice I specified sheet names in the code, you can change that according to your needs

Applescript get all values of Excel column

I am trying to store all the values of an excel column in an array.
set rangeDate to {value of range "A14:A100"}
repeat with date in rangeDate
if (date as string is equal to "01/01/2001") then
log "It works"
end if
end repeat
In my Excel I do have an exact date of 01/01/2001 formatted in the specified columns. When I remove the range and it is just cell A14 (where the date is) it works. But when I include the range A14:A100 it doesn't work.
I am new to applescript, I guess that it doesn't store the values as array values and instead a string object? Any help would be appreciated
You have 4 issues :
1) value of range should not be between {}, but between ()
2) 'Date' is a reserved word in Applescript, so you should not use it as the variable in the loop. I replaced it with 'myDate'.
3) instead of converting your date to string to compare with "01/01/2001", it is quicker to keep comparing 2 dates, and then, compare with the date "01/01/2001"
4) I think it is a bug (at least with my Excel version), but the rangeDate variable is not a list of dates as expected, but for me a list of list : {{01/02/01},{02/02/01},………} Therefore, each member of 'rangeDate' is not a date, but a list made on one item which is a date ! I am not sure, but it could also be that range definition could be a list of ranges... So I am using item 1 of sub list.
Anyway, script bellow is working :
tell application "Microsoft Excel"
activate
tell active sheet of document 1
set rangeDate to (value of range "A14:A100")
repeat with mydate in rangeDate
set TheDate to item 1 of mydate
if TheDate = (date "lundi 1 janvier 2001 00:00:00") then
log "It works"
end if
end repeat
end tell
end tell
Quickly getting the values of a range of cells is great news! But even better is that you can fill in the values of a range by defining the value of that range. This is SO MUCH FASTER than doing it one cell at a time.
When I tried getting the value of a column (a range of cells), I received a list of lists. Each item in the list had only one value - that is the value of the cell.
To speed up complex operations, once you've got the list of values, take the process out of the "tell Excel" block and let AppleScript do the calculations. Then turn the result back into a list of lists and define the value of the range in Excel.
I had a problem reading ranges with some cells containing #VALUE! (failed formulas). I didn't find a solution on the Internet, so I thought it would be a good idea to share my solution here. Comments & improvement are surely welcome. I'm inclined to think there is a more straightforward solution to the problem than this. :)
Getting all values with value of range can lead to a problem messing up the output of the script. AppleScript doesn't consider a cell's content "#VALUE!" (= missing values) a value since it is, well, missing. Therefore the script doesn't include the cell's content in the list of values. This obviously messes up the cell order in the values list, since it has less items than the actual range has cells. In this situation it is quite impossible to return each value to its original cell in the workbook. Adding ”of ranges” to the code includes all cells with missing values solving the problem.
N.B. The values will be displayed as a one-dimensional array. Handling multi-column ranges requires more work. Nonetheless the missing values are included.
set celVals to (value of ranges of range "A1:A4")
E.g. {2.2.2022, 1.1.2011, missing value, 3.3.2033}
In order to return the values back to the workbook it is required to build back the list of lists. A missing value will be written to its cell as an empty string. Of course the original (failed) formula can be written instead, if needed.
N.B. again. This code applies to one column situation only. A little more is needed to put back a multi-column range. I'm sure you'll manage. :D
set returningCelVals to {}
repeat with i from 1 to count of celVals
set end of returningCelVals to {item i of celVals}
end repeat
set value of range ("A1:A4") to returningCelVals
EDIT: I knew there is a better solution. Here it is:
set celVals to string value of range "A1:A4"
String value gives a two-dimensional array of values and error messages of the range. String value gives also e.g. cell's currency symbols, so it is perhaps not suitable to all situations.

Excel VBA should run excel function - RIGHT LEN

I would like to put the below coding into a vba like a function. There is a bunch of data created already by VBA, and when the VBA does its work, then the following function should be run, but i dont know how to add to my vba so that the function always runs as long as data contains. The macro i created already puts the datasheet together, now instead of creating the below with lenthy codings, i just want my macro to run the below, like a man who clicks on the below right hand corner of the cell which contains the below function.
It should be something: Activesheet.ForulaR1C1 = "=RIGHT(AY4,LEN(AY4)-FIND(".",AY4))" something. Can someone help me? Thanks
ORIGINAL FUNCTION TO BE RUN "=RIGHT(AY4,LEN(AY4)-FIND(".",AY4))"
This is where I am at now:
Sub Project_numbers()
Dim j As Integer
Zorro = Range("AY" & Rows.Count).End(xlUp).Row
o = 4
Worksheets("MJE").Range("AF" & o).FormulaR1C1 = "=RIGHT(AE4,LEN(AE4)-FIND(".",AE4))"
o = o + 1
End Sub
You have a couple of problems here. The biggest is that you've got quotation marks in your formula. VBA reads these as the end of the string, so it's interpreting your formula as two separate text strings: =Right(AE4,LEN(AE4)-FIND( and ,AE4)), separated by a .. This isn't a structure VBA can do anything with, so it's going to fail at that point.
When you're inserting a formula with VBA that contains quotation marks, you need to use two quotes together to indicate that it's a literal quote mark that's part of the string, rather than the end of the string:
"=RIGHT(AE4,LEN(AE4)-FIND(""."",AE4))"
The second problem is that you're using the FormulaR1C1 method, which expects cell references to be given in R1C1 (row#column#) notation, rather than A1 notation, but then passing it a formula that uses A1 notation. Again, this is going to confuse the issue and produce errors.
I'm guessing you used the macro recorder to get the syntax, then inserted your own formula? The macro recorder, for some weird reason, loves to use the R1C1 reference style, but we can use a different method for written code.
The full line you need is:
Worksheets("MJE").Range("AF" & o).Formula = "=RIGHT(AE4,LEN(AE4)-FIND(""."",AE4))"
EDITED TO ADD:
With further information, specifically that you need the range referenced to change as you loop, you have some options on how to do it.
1. Use the R1C1 reference style
This allows you to include relative references in formulae easily. You'll use R to designate the formula's row, and C to designate its column; so a cell that referred to itself would simply be =RC. You can follow the R and C with numbers to designate specific rows and columns, so cell B2 would be =R2C2 - row 2, column 2. More usefully, you can use =R[#]C[#] to offset your formula by a certain amount.
In your formula, assuming it's always going to be looking at column AE but whichever row the formula is entered into, your line would be:
Worksheets("MJE").Range("AF" & o).FormulaR1C1 = "=RIGHT(RC31,LEN(RC31)-Find(""."",RC31))"
2. Build your formula from variables.
You already have a variable you can use, o, so we can combine that with the rest of the string to get the appropriate references. It's harder to read, though...
Worksheets("MJE").Range("AF" & o).Formula = "=RIGHT(AE" & o & ",LEN(AE" & o & ") - FIND(""."",AE" & o & "))"
Personally, I find this method rather cumbersome to work with, but it's an option.
3. Assign the formula to your entire range as a single operation
Personally, I prefer this option; I find it to be the neatest one. I'm assuming, from your formula, that your data starts on row 4, and you want the formula to go into every cell between AE4 and the end of your data, which is stored in Zorro. You can use this line to add the formula in one go:
Worksheets("MJE").Range("AF4","AF" & Zorro).Formula = "=RIGHT(AE4,LEN(AE4)-FIND(""."",AE4))"
The cell references will update automatically for each row. There's no need for a loop with this method - of course, if you're looping anyway, that may be no great saving.

vba excel vlookup: lookup value in stored array, lookup table in excel, output value to array

I am using vlookup to populate an array in vba.
The array (InfArray) is an ~100 row by 3 column array. The first column of the array is already populated with integer values. These integer values correspond to a name. In one of my excel sheets I have a table that has each integer id listed with its corresponding name. So I want to use the vlookup function to check the id integer and populate the second column of the array with the actual name.
Here is the code statement I have to assign the second column (original bad code):
For y = 1 To UBound(InfArray,1)
Set InfArray(y,2) = Application.WorksheetFunction.VLookup(InfArray(y,1), NameSheet.Range("B2:C244"), 2, False).Value
Next y
It is giving me a Object variable or With block variable not set error.
When I cursor over the code text after running, I see that the
NameSheet.Range("B2:C244")
is where the object variable or with block variable not set error is located. This is really confusing. I put a
Debug.Print NameSheet.Name
In the code prior to the error and it is giving me the correct name of the excel sheet in question. So the code must be looking in the right worksheet, but somehow it is not getting the range...?
I'm lost, please help
EDIT: The error was a typo in the code
NameSheet.Range("B2:C244")
should have been
NamesSheet.Range("B2:C244")
Note the 's' at the end of NameS
It now works with the edits suggested
Working code line:
For y = 1 To UBound(InfArray,1)
InfArray(y,2) = Application.WorksheetFunction.VLookup(InfArray(y,1), NamesSheet.Range("B2:C244"), 2, False)
Next y
Apologies for the stoopid error.
Thanks for you help.
Get rid of the Set statement. It should only be used with object variables.
But also...
Piercing the boundary between VBA and Excel 100 times in a loop is not an efficient design. It would be much better to grab your table once, place it in a VBA array, and then just spin through this additional array to find the lookup values.
Remove the .Value from the VLOOKUP function. The Range.Value property is not part of VLOOKUP.
For y = 1 To UBound(InfArray,1)
InfArray(y,2) = Application.VLookup(InfArray(y,1), NameSheet.Range("B2:C244"), 2, False)
Next y
I've also reduced to down to Application.VLookup which is all that is necessary.

Excel - Convert String with if condition to a formula

I'd like to use something like the EVALUATE-Function in Excel for if-statements.
I've got the following issue: I'd like to use Excel to validate my data. I've got three sheets:
the real data I'd like to check. Each row represents a customer and each column some data. The columns have specific names like “age”, “name”, …
the description of the checks I’d like to perform. Each row represents one check and I’ve got 3 columns: 1 check_id – an identifier of each check; 2 check_desc – a description of the check that every normal person can understand like “Age below 18”; 3 rule – the Excel Formula as a string like If(age<18, “error”, “no error”)
the place where sheet 1 and 2 should come together. Each row should represent one customer and each column one check.
Now, if I’ve got for example check_1 “If(age<18, “error”, “no error”)” and the customer data 10 and 20, then the check for the first customer should fire and the check for the second shouldn’t.
If the data is changed, and the age is set from 10 to 18, then everything should be fine, or if the rule is changes to “If(age<21, “error”, “no error”)” then the new condition should be applied to all data.
Is something like this possible?
With the evaluate function only ‘simple’ formulas work.
Thanks in advance,
Martin
Attached you can find the
Excel-Sample File
You will definitely need some VBA here. Make a custom EVAL function:
Public Function EVAL(ByRef Rng As Range, Formula As String) As Variant
Dim RngAddress As String
RngAddress = "'" & Rng.Parent.Name & "'!" & Rng.Address(External:=False)
EVAL = Evaluate(Replace(Formula, "$", RngAddress))
End Function
Then you can easily evaluate your values with formulas passed as text ($ is for parameter):
=EVAL(A1, "IF($<21,""error"",""no error"")")
(note the escaped double quotes). But you would rather pass formula from another cell - then you can specify formula in cell with single quotes:
IF($<21,"error","no error")
=EVAL(A1, B1)
I personally would rename check_desc!B2 to "Check_1" (named range) and then refer to that. You can use the INDIRECT function as well once you've renamed your column header "Check_1" as well.
Note: the value in this case should be "18" instead of "age below 18". You can of course change the number format to "age below "0.
If the relations are changing too I would insert a table that would have uniform formulae changing in each cell when changed in one cell.
The only issue you would then face is the non-expanding nature of your table. You can use VBA for this, but maintaining formulae increases your accountability even if it would be slightly easier not to deal with nasty nested functions.

Resources