Getting list of values from a cell - vba

I have an Excel sheet on which I have created a list consisting of many values. Also I have created a macro which shows a userform in which those values are hard-coded.
Now I want that those values in the form to be automatically/programatically/dynamically added to my userform list, so that in the future, if I want to decrease the values from the list, then I would not have to change the macro again.
I have been searching for the answer but I have been unsuccessful in finding what I am looking for.
I have recorded this macro, but I don't know how to retrieve values from it:
Sub Macro7()
'
' Macro7 Macro
'
'
Range("E1").Select
ActiveSheet.Range("$A$1:$AE$175").AutoFilter Field:=5
End Sub

The macro you've specified will turn on autofiltering for your active worksheet. This will provide column headers that will allow the user to filter to something of interest.
Assuming that this kind of filtering of the worksheet is what you want, you can use something like:
Dim r As Range
'Note: set r to something useful, such as worksheet.Cells
Dim vis As Range
Set vis = r.SpecialCells(xlCellTypeVisible)
'now vis holds a special "Range" object referring to the visible cells.
'since (auto) filtering hides some cells, this vis range will help show only the cells that remain visible.
'the output of SpecialCells, you should assume holds a complex Range,
'which is composed of multiple Areas that are wrapped in one single Range object
'the separate areas help you distinguish the visible cells from the hidden cells
'fyi, various safety checks you can do: vis Is Range, vis Is Nothing
Dim a as Areas
Set a = r.Areas
Dim cr as Range
For Each cr in a
'cr refers to a single (i.e. normal and contiguous) area range
'where you can use cr.Row, cr.Column, cr.Rows.Count, cr.Columns.Count
Next
So when you do filtering, you can use SpecialCells(xlCellTypeVisible) to reveal the non-hidden cells, which are represented as have a range that wraps areas that represent contiguous ranges.

With a userform named UReports that has a listbox named lbxReport, use code like this to fill the listbox with values from column E
Sub ShowUf()
Dim ufReports As UReports
Dim rCell As Range
Dim colUnique As Collection
Dim i As Long
Set ufReports = New UReports
Set colUnique = New Collection
'loop through the cells in column E
For Each rCell In Sheet1.Range("E2", Sheet1.Cells(Sheet1.Rows.Count, 5).End(xlUp)).Cells
'Collections can't have duplicate keys, so we try to add all the values. If there
'are duplicates, the 'On Error' ignores them and we're left with a collection of
'only unique values from column E
On Error Resume Next
colUnique.Add rCell.Value, CStr(rCell.Value)
On Error GoTo 0
Next rCell
'loop through the collection and add them to the listbox
For i = 1 To colUnique.Count
ufReports.lbxReport.AddItem colUnique.Item(i)
Next i
'Show the form
ufReports.Show
End Sub

Related

looping through each COLUMN and finding highlighted cell

I am having difficulty looping through each column before looping through the next row. The number of columns is fixed (A:K) with an unknown number of rows. The goal is to find highlighted cells (no distinct color.. and I figured the best way to do this is to code "If Not No Fill") and copy that whole row to another workbook. This is what I have so far and I am stuck:
Option Explicit
Sub Approval_Flow()
Dim AppFlowWkb As Workbook, ConfigWkb As Workbook
Dim AppFlowWkst As Worksheet, ConfigWkst As Worksheet
Dim header As Range, headerend As Range
Dim row As Long, column As Long
Set AppFlowWkb = Workbooks.Open("C:\Users\clara\Documents\Templates and Scripts\Approval Flow Change Log.xlsx")
Set ConfigWkb = ThisWorkbook
Set AppFlowWkst = AppFlowWkb.Sheets("Editor")
Set ConfigWkst = ConfigWkb.Worksheets("Approval Flows")
With ConfigWkb
Set header = Range("A7").Cells
If Not header Is Nothing Then
Set headerend = header.End(xlDown).row
For row = 7 To headerend
For j = 1 To 11
'if cell is filled (If Not No Fill), copy that whole row to another workbook
End With
End Sub
I am getting an error with the Set headerend line, but I am trying to select the last row to use it in my for loop. I appreciate any help and guidance. Thanks in advance!
You should be able to adapt this to suit your workbooks, see the comments for details
Dim aCell as Range
' Use UsedRange to get the variable number of rows,
' cycle through all the cells in that range
For Each aCell In ActiveSheet.Range("A1:K" & ActiveSheet.UsedRange.Rows.Count)
' Test if fill colour is white (none)
If Not aCell.Interior.Color = RGB(255,255,255) Then
' Insert new row in target sheet (could find last row instead)
ActiveWorkbook.Sheets("ThisOtherSheet").Range("A1").EntireRow.Insert
' Paste entire row into target sheet
aCell.EntireRow.Copy Destination:=ActiveWorkbook.Sheets("ThisOtherSheet").Range("A1")
End If
Next aCell
Alternatively to find the last row, if you know the range is continuous (no blanks) then you can use End(xlDown) like you had done, and like below
For Each aCell In ActiveSheet.Range("A1:K" & ActiveSheet.Range("K1").End(xlDown))
I'd guess you don't want to copy the same row multiple times if you've already copied it. You could do this by keeping an array or string with previously copied row numbers and checking before copying again, or use Excel's unique functions to strip the list down after copying.
Hope this helps.
Aside:
You're using a With block but not taking advantage of it, you need to put a dot . before your Range objects to specify that they're in your With sheet. Like so
Dim myRange as Range
With ActiveSheet
Set myRange = .Range("A1:C10")
End With
You're mixing the types.
It looks like you just want to use the Row that the Header data ends on.
Take out the .Row there, since you're setting headerend to be a cell address, not a specific value. Then change For row = 7 To headerend to For row = 7 To headerend.Row
Or, change Dim Headerend as Range to ...as Long and just do headerEnd = header.End(xlDown).Row (don't use Set)

Highlight unique values based on another range

Column 1 is in Sheet1 and column 2 is in Sheet2. If the value is not found , then highlight that cell. I am trying to do a vlookup comparing two columns. I think the Syntax is incorrect. Please see my code I was trying below:
Option Explicit
Sub VlookupColoums()
' declarations
Dim lookFor As Range
Dim srchRange As Range
Dim I As Long
Dim vtest As Variant
' start
Set lookFor = Sheets("Sheet1").Range("A13").End(xlUp)
Set srchRange = Sheets("Sheet2").Range("A2").End(xlUp)
vtest = Application.VLookup(lookFor.Rows.Count, srchRange.Rows.Count, 2, False)
' process
For I = 1 To lookFor.Rows.Count
If IsError(vtest) Then
srchRange.Interior.Color = 4
Else
Exit Sub
End If
Next I
End Sub
Assuming you have data on Sheet1!A1:A15 and Sheet2!A1:A10.
Also assuming you want to highlight unique cells (ones withouth at least one identical in the other list) on Sheet2.
Basically you want to format all the cells that if counted on the other list comes up with 0. The steps:
Select all the cells to be evaluated on Sheet2
Go to Home/Styles/Conditional Formatting
Select New Rule, then Use a formula to determine...
Enter this formula: =COUNTIF(Sheet1!$A$1:$A$5,A1)=0
Click on the Format button, and set up a formatting for the unique cells
OK
Profit. :)

VBA Copying cells to another worksheet where cells have the same value

I have two worksheets I'm working with with long serial numbers as the cell values. One sheet (Sheet1) has a list of each individual serial number hyperlinked to a webpage referring to that item. This list ranges from A1:A31.
The second sheet (Sheet2) has a massive list of those same serial numbers, but in range G1:G102. The difference is that this list is not hyperlinked, and the serial numbers sometimes show up multiple times. There are also some areas where a cell is blank, so it splits up the continuous column of data.
I would essentially like to write a macro that takes the first list in Sheet1, and for each cell, it compares it to each cell in Sheet2 column G. Then, if the values match, I would like to copy the hyperlinked cell from Sheet 1 and paste it to that cell with the same value in Sheet2. Therefore, Sheet2 column G now has a fully populated list of hyperlinked serial numbers.
Can anyone help me with this? This is what I have so far...doesn't seem to work:
Sub CopyHyperlinks()
Dim cell As Excel.Range
Dim myRange As Excel.Range
Dim newRange As Excel.Range
Set myRange = Excel.ThisWorkbook.Sheets("Contents").Range("A1:A31")
Set newRange = Excel.ThisWorkbook.Sheets("Sheet1").Range("G1:G102")
For Each cell In myRange
If myRange.Cells.Value = newRange.Cells.Value Then newRange.Cells.Value = myRange.Cells.Value
Next cell
End Sub'
See this little function. Put this:
Function GetHyperLinkAddress(rng As Range) As String
Dim hl As Hyperlink
For Each hl In rng.Parent.Hyperlinks
If hl.Range.Address = rng.Address Then
GetHyperLinkAddress = hl.Address
Exit Function
End If
Next hl
GetHyperLinkAddress = "Not Found"
End Function
in a module. In the Spreadsheet, add
=GetHyperLinkAddress(Cell#)
Next to the cells with the hyperlink. You could then just use a vlookup to match.

Excel - Variable in Range

The variable tablelength counts how many items are in a table of mine. I want to select my entire table, but it varies in sizes so my range has to include a variable. I've googled a lot and searched this site (Using variables in Excel range <- that method looked promising but didn't work). Below is a snippet of my code, but includes everything that is relevant.
Private Sub CommandButton1_Click()
Dim shSource As Worksheet
Dim shDest As Worksheet
Dim tablelength As Integer
Set shDest = ThisWorkbook.Sheets("Sheet2")
'here comes some code that determines the value of tablelength, which is 8 in this case
shDest.Range("L" & "4" & ":" & "M" & tablelength).Select
End Sub
I appreciate the help.
edit: the debugger highlights the shDest.Range code.
Unless you need tablelength variable somewhere else in the code, you could try using:
shDest.Range("L4").CurrentRegion.Select
CurrentRegion.Select will select all cells starting from "L4" until it reaches a blank row and column, so providing your tables are surrounded by blank cells this should select the whole table regardless of the size
Here you go, try this:
ActiveSheet.Range(Cells(2, 3), Cells(10, 4)).Select
Taken from http://support.microsoft.com/kb/291308
The first parameter to Cells is the row and the second is the column as a number.
So for you it would look something like this:
shDest.Range(Cells(4, 12), Cells(tablelength, 13)).Select
If it's a proper Table on the spreadsheet, and not just cells formatted to look like a table, you can directly refer to the 'live' size of the table in your code without jumping through all these hoops.
In your VBA code,
The 'Table' is referred to as a ListObject
You can declare a new ListObject, and look up its DataBodyRange.Rows.Count
This should work:
Sub MyMacro()
Dim Tabl As ListObject
Set Tabl = Worksheets("Sheet1").ListObjects("Table1")
MsgBox Tabl.DataBodyRange.Rows.Count
End Sub
You can also set a range variable to refer to the 'Data' range. You need to use the following code.
Dim Rng As Range
Set Rng = Worksheets("Sheet1").ListObjects("Table1").DataBodyRange
Now Rng.Cell(1,1) or Rng.Range("A1") refers to the top left cell of the data body and so on and so forth...

Copy/Paste cells next to cells that have certain string

I am trying to look up cells in a certain column that have a string (e.g. Names), copy the corresponding cells in the column to its right (i.e. offset(0,1) ), then paste it to a column in a different sheet. I have the following code to find the range variable that I want. However, I can't select it from a different sheet!
When I use Sheets(1).MyRange.Copy, it doesn't accept it. Am I referring to the range in a wrong way? What am I doing wrong?
Here's code that I use to get MyRange:
Option Explicit
Sub SelectByValue(Rng1 As Range, Value As Double)
Dim MyRange As Range
Dim Cell As Object
'Check every cell in the range for matching criteria.
For Each Cell In Rng1
If Cell.Value = Value Then
If MyRange Is Nothing Then
Set MyRange = Range(Cell.Address)
Else
Set MyRange = Union(MyRange, Range(Cell.Address))
End If
End If
Next
End Sub
Sub CallSelectByValue()
'Call the macro and pass all the required variables to it.
'In the line below, change the Range, Minimum Value, and Maximum Value as needed
Call SelectByValue(Sheets(1).Range("A1:A20"), "Tom")
End Sub
One More Question: Rather than specifying the exact range to look at (e.g. "A1:A20"), I would LOVE to look at all of column A. But I don't want to use ("A:A") so it wouldn't look at all rows of A. Isn't there a method to look only in cells that have entries in column A?
Thank you VERY much.
Al
You only need MyRange.Copy.
To restrict only to cells in column A which might have values, you could use
With Sheet1
Set rngToSearch = Application.Intersect(.Columns(1), .UsedRange)
End With
...or maybe look at .SpecialsCells()