VBA conditional cell selection - vba

I was having a play around with excel 2007 VBA and was hoping to create a Macro that generates a random number, then outputs a string based on the number generated. For example,
Number String
1 Athena
2 Belerephone
3 Castor
4 Dionysos
If the random number is 4, the output would be Dionysos, 1 would be Athena and so on.
Basically, I want the Macro to search through the "Number" column, find the cell that matches the randomly generated number, then output the string in the cell to its right.
I have a table of a similar nature in my Excel worksheet.
So far I have not had much success at doing this, any thoughts?

With your data in A1 thru B4, use:
=VLOOKUP(RANDBETWEEN(1,4),A1:B4,2,FALSE) or its VBA equivalent
EDIT#1 :
With the upper bound of the table stored in cell D3 :
=VLOOKUP(RANDBETWEEN(1,D3),INDIRECT("A1:B" & D3),2,FALSE)

You can use application.worksheetfunction.vlookup to perform a vlookup within your macro, and use the 1+Int(10 * Rnd()) function to return random numbers from 1 to 10 (and possibly 11, but statistically unlikely).

Related

How to match multiple columns and get values in Excel [duplicate]

This question already has answers here:
Vlookup using 2 columns to reference another
(2 answers)
Closed 5 years ago.
I need to match Column A and Column B values in Sheet 1 with Column A and Column B values in Sheet 2. If both are same then Copy C values from Sheet 2, and paste in Sheet 1 in C. I will enter values manually in sheet 2 Column C.Here each country will have 2 or more Number. So, both Column A and Column B must match.
I used the formula below. But not working. Most of the Column A and B values are not in order. Help me
=INDEX(Sheet2!$C:$C; MATCH(Sheet1!$A2:B2; Sheet2!$A:$B; 0);COLUMNS($A:B))
You can use the following formula to return what you're looking for. It is an array formula so will need to be entered with Ctrl+Shift+Enter
=INDEX(Sheet2!$C$2:$C$22; MATCH(1; (Sheet2!$A$2:$A$22=Sheet1!$A2)*(Sheet2!$B$2:$B$22=Sheet1!$B2);0))
As it is an array formula I recommend defining your ranges from beginning to end instead of just selecting the whole column. Non-array formulas Excel actively finds the beginning and end of the range and only calculates that subset; however, with array formulas it considers the whole range (even if there's nothing in it) so it can suddenly take a very long time even when there isn't much being calculated
Use the following as a matrix formula:
=INDEX(Sheet2!$C:$C; MATCH(Sheet1!$A2&$B2; Sheet2!$A&$B; 0))
Paste this into cell C2:
=INDEX(C2:C22,MATCH(G2&H2,A2:A22&B2:B22,0))
and use Ctrl+Shift+Enter instead of Enter since it's an array formula.
Then copy that cell as many rows down as needed.
Here are some more examples.

Auto Fill Row B with the last four characters of Row A

So basicly i want a VBA script to fill Row B with the last four characters that are in Row A
RowA contains a telephone number with around 12 numbers in it.
Assuming that you meant to say
I have a series of telephone numbers in column A. I would like to
create a second column in which I have just the last four digits of
these numbers. I am new to Excel. Could someone please help me get
started on this?"
The answer would go like this:
In Excel you can create formulas that compute "something" - often based on the contents of other cells. For your specific situation, there is a function called RIGHT(object, length) which takes two arguments:
object = a string (or a reference to a string)
length = the number of characters (starting from the right) that you want.
You can see this for yourself by typing the following in a cell:
=RIGHT("hello world", 5)
When you hit <enter>, you will see that the cell shows the value world.
You can extend this concept by using a cell reference rather than a fixed string. Imagine you have "hello world" in cell A1. Now you can put the following in cell B1:
=RIGHT(A1, 5)
and you will see the value "world" in B1.
Now here is the cool trick. Assume you have a bunch of numbers in column A (say starting at row 2, since row 1 contains some header information - the title of the column). Then you can write the following in cell B2:
=RIGHT(A2, 4)
to get the last four digits. Now select that cell, and double-click on the little box in the bottom right hand corner:
Like magic, Excel figures out "you want to do this with all the cells in this column, for as many rows as there is data in Column A. I can do that!" - and your formula will propagate to all cells in column B, with the row number adjusted (so in row 3, the formula will be
=RIGHT(A3, 4)
etc.
Try
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
With ws.Range("B2:B99")
.Formula = "=Right(A2, 4)"
.Value = .Value
End With

VBA to check for blank cells in columns based on value in another column

Given
O 1 2 3 A
A 4 5 6 B
B 7 8 9 D
O 3
C 15
T 18
I'm looking for VBA code to validate that when column A contains a value that the remaining columns also contain values and when it doesn't contain a value, that columns 2 & 5 also contain values but 3 & 4 don't.
I've simplified the example, in a real sheet there will be many more columns and rows to check.
I've considered COUNTIF and INDEX/MATCH and array forumlas but from my understanding these all work on single columns at a time.
I want to do something like WHEN A1:An<>"" THEN COUNTBLANK(B:E) ELSE COUNTA (C:D)
Is the best way to use autofilter using blanks in A and then countblank and then a second autofilter for values in A.
Thanks
You can do it with a couple of nested IF formulae as follows:
=IF(A1<>"",
"A not empty, "&IF(COUNTBLANK(B1:E1)=0,
"B:E not blank",
"B:E have blanks"),
"A blank, "&IF(AND(COUNTBLANK(B1)+COUNTBLANK(E1)=0,
COUNTBLANK(C1)+COUNTBLANK(D1)=2),
"Columns 2&5 have values and Columns 3&4 don't",
"but condition not met"))
The reason for going down the VBA route is that I want a generic reusable function as opposed to a formula I copy between cells and sheets changing the columns etc along the way ending up with a lot of duplicate code.
So something that takes a column to test and a value to test it with. Third parameter would be a range of columns to validate, and the fourth parameter the validation.
I don't want any solution to have the columns hard coded and I don't want intermediate totals at the end of rows. This is fairly easily achieved in Excel itself...
The reason for trying to use countblank is that I can apply it to a range.
After a lot of searching I discovered this (the columns don't match the original example)
=SUMPRODUCT((A2:A19<>"")*(B2:D19=""))
=SUMPRODUCT((A2:A19="")*(D2:D19=""))
=SUMPRODUCT((A2:A19="")*(B2:C19<>""))
Nice huh? I just need to convert it into VBA now.
Thanks

copy only those rows whose string len is > 6 in b column cell values

is it possible to copy only those rows which has string length more than 6 characters and paste them to a new sheet? The task is I have to remove all the unwanted characters in the rows. the range is 2 to 4000 something like that
I was using looping and mid function to do that which i found on google because I found only looping solution to that on google, because I only need numbers in each cell of B column and remove all other character except &,/, ,,. Then after cleaning up all ce
lls in B column I need to check the number of digits in each row of B column and if it contains more than 6 it should be copied to new sheet and it may contain blank cells too in between
a b c
6451 1234567 somevalue
4563 12345 somevalue
3245 123456789 somevalue
2345 1234 somevalue
Now I have to copy the 1 and 3 rd row but not the other rows as length of string is less than 7. I have to check only the B column and copy the entire row if it has more than 6 digits
I think what your boss is trying to say (not very well, btw) about using variant arrays, etc. instead of worksheets is to keep it in VBA. Read in the data once and manipulate it within VBA instead of pasting and manipulating data on a worksheet to get the desired result. This of course extends to anything outside of making calls to Excel, not just variant arrays. Perhaps you are often looping through cells one by one and he is trying to say he'd prefer if you dumped a range into a variant array and worked on it inside of VBA instead.
Of course, the best method depends on the task on hand, in my opinion.
As for your row question, it's a little unclear what you're trying to do (try to be careful how you use the words 'row' 'cell' and 'column'). A row cannot have a 'string length' so I am assuming you mean cell. Please confirm.

Replace or recode several different values by a single value in an Excel file

I have an Excel worksheet which contains data in several columns. For a specific column, I will need Excel to replace all values between, say 10 to 15, by the value 1 and values between 16 and 20 by the value 2 and so forth.
I know how to do it for a single value; ie: I can replace value 10 by 1, 11 by 1 and so on. But this will be a tedious exercise. Are there some lines of codes that can execute this task?
Thanks for your help.
regards,
Ali
If you do not need to automate this with a macro or repeat often, you can do this quickly right on the spreadsheet.
Insert a new column to the right of the column to change. Let's say the column was A and you just created a new column B.
Enter the formula =INT(A1/5) - 1 in cell B1.
Copy this formula to all cells in column B for the extent of the cells in column A.
Copy the cells in column B and paste to column A using right-click, "Paste special...", Values, then click Ok.
Delete column B (this is a temporary/work column).
This will replace the values in column A with the adjusted values in column B. Proceed with any other columns.
Here's a quick and dirty way, that will have to be modified based on what values you really want to change to and from. This converts 11 to 15 to 1, and 16 to 20 to 2, etc.
You'll probably want to put a button on the spreadsheet, and then right click and choose "View Code". Then enter the following between the Sub and End Sub statement. "RangetoChange" is the name of a named range, OR you can put in the range itself, like "A1:A100". Once it's all entered, then you just get out of design mode (that you entered to place the button), then click the button. Make sure that you change the formula to what you really want the result to be.
Dim A() As Variant
Dim i As Integer
A = Range("RangetoChange")
For i = 1 To (UBound(A) - LBound(A) + 1)
A(i, 1) = (A(i, 1) \ 5) - 1
Next i
Range("RangetoChange") = A