VBA iterate drop down list - excel

I have a spread sheet with J1 being a drop down list. Content in row 8-14 would change based on what you choose in J1. I need to iterate through all values in the drop down list and copy all the corresponding rows to a new workbook. the copy paste part is working, but I am having problem iterating through the drop down list. particularly, I need some help to define Formula1. I am using excel 2010. Here is my code. Thanks in advance
Sub iterate_dropdown()
Dim inputRange As Range
Dim c As Range
Dim Current As Range
Set inputRange = Evaluate(Workbooks("sample.xlsm").Worksheets("Credit Research Journal").Range("J1").Validation.Formula1)
For Each c In inputRange
Workbooks("sample.xlsm").Worksheets("Credit Research Journal").Range("J1").Value = c.Value
Workbooks("sample.xlsm").Sheets("Credit Research Journal").Activate
Workbooks("sample.xlsm").RefreshAll
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
Cells(8, 1).Resize(FinalRow - 7, 10).Copy
Workbooks("Book2.xlsm").Sheets("Sheet3").Activate
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Set Current = Cells(NextRow, 1)
Current.PasteSpecial xlPasteValues
Next c
End Sub

I did some experimenting with the code you posted, and it seems you were pretty close. I discovered that the step where you were getting inputRange was including an equals sign (=), which then caused the Evaluate function to fail.
Here is the code I used:
Sub iterate_dropdown()
Dim inputRange As Range
Dim c As Range
Dim Current As Range
Dim strRange As String
Dim strRange2 As String
strRange = Worksheets("Credit Research Journal").Range("J1").Validation.Formula1
strRange2 = Replace(strRange, "=", "") 'Get rid of the equals sign
Set inputRange = Evaluate(strRange2)
For Each c In inputRange
Workbooks("sample.xlsm").Worksheets("Credit Research Journal").Range("J1").Value = c.Value
Workbooks("sample.xlsm").Sheets("Credit Research Journal").Activate
Workbooks("sample.xlsm").RefreshAll
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
Cells(8, 1).Resize(FinalRow - 7, 10).Copy
Workbooks("Book2.xlsm").Sheets("Sheet3").Activate
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Set Current = Cells(NextRow, 1)
Current.PasteSpecial xlPasteValues
Next c
End Sub
I used two string variables strRange and strRange2 so that you can easily step through with the debugger and see what is happening.
Also I am assuming that your dropdown list is being populated by values that are references to other cells.

Related

VBA - Remove cell that contains word from same column

I've seen similar posts out there but not quite the same and seem to be confused on the results I'm getting...
I essentially need to de-dupe a column on LIKE words, so it's somewhat straightforward but apparently not as easy as I thought.
I have a dataset like soo...
When I run my macro it removes rows (as I intended), but doesn't seem to remove all the rows or the wrong rows...
It actually removes the highlighted/yellow rows
I was thinking it should actually remove something like the bottom rows.. where it would keep "aerospace" but remove "aerospace 2019", since the 2019 is kinda redundant and not applicable to me.
My macro is simple, but I thought it would do the trick... what am I doing wrong?
Sub container()
Dim ws As Worksheet, rw As Long, col As Long, i As Long
Set ws = ActiveSheet 'or whatever
i = 2
'For col = 2 To 5 'placeholder in case multiple columns are needed - remove Set col above
For rw = 2 To ws.Cells(Rows.Count, 1).End(xlUp).Row 'from row 1 til last non-empty row
v = ws.Cells(rw, 2).Value 'set range
If Cells(i, 2).Value Like v Then 'determine if the cell contains the value of the word
Cells(i, 2).EntireRow.Delete 'delete
i = i + 1
End If
Next rw
'Next col
End Sub
After Ron's post I was able to create the below, but appears I'm still stuck. I think I've just been looking at this too long.
Sub container()
Dim ws As Worksheet, rng As Range, i As Long, rw As Long
Set ws = ActiveSheet 'or whatever
Set rng = ws.Range("B2:B" & ws.Cells(ws.Rows.Count, "B").End(xlUp).Row) 'set array range
i = Range("B" & Rows.Count).End(xlUp).Row
For rw = ws.Cells(Rows.Count, 1).End(xlDown).Row To 2
v = ws.Cells(rw, 2).Value
If InStr(1, v, rng) > 0 Then
cell.EntireRow.Delete
i = i - 1
End If
Next rw
End Sub

Delete Cell based off another Cell that is a date

Working in Excel VBA.
I'm trying to delete a cell, if there is a date in another cell via VBA.
Or another way to put it, I'm trying to delete a cell, if another cell has ANYthing in it. (As it's either a date, or not.)
Here's my code - I just don't know how to recognise any date in the cell.
Sub Upload1ClearADP()
Dim LastRow As Long, x As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For x = 2 To LastRow
If Cells(x, "G").Value = "Date" Then
Cells(x, "U").ClearContents
End If
Next x
End Sub
You're currently checking for a string Date, not technically an actual date.
Here's your code written to check if it's a date OR is empty:
Sub Upload1ClearADP()
Dim LastRow As Long, x As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For x = 2 To LastRow
If IsDate(Cells(x, "G").Value) or Cells(x, "G") <> "" Then
Cells(x, "U").ClearContents
End If
Next x
End Sub
Edit: As #Harun24HR points out in the comments, the IsDate() is unnecessary, since you check if the cell is not empty (<> ""). I just wanted to put it there to introduce the IsDate() function.
Edit 2: You can also use SpecialCells() to do the clearing in one line:
Sub Upload1ClearADP()
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Dim dataRng As Range
Set dataRng = Range(Cells(2, "G"), Cells(LastRow, "G"))
' Use 14 because it's 14 columns to the right from
' Column G to U
dataRng.SpecialCells(xlCellTypeConstants).Offset(0, 14).ClearContents
' If you have formulas *and* constants in column G, use:
' Union(dataRng.SpecialCells(xlCellTypeConstants), _
' dataRng.SpecialCells(xlCellTypeFormulas)).Offset(0,14).ClearContents
End Sub

I have to run my code several times for it to execute entirely

I'm not sure whether it's because I'm using a mac or the code is wrong, but the rows aren't identifying properly, and therefore not deleting or pasting it into the other spreadsheet. I have to run the code three times for it to properly go through it and copy/paste and delete the cells into the other spreadsheet.
Many thanks!
here is the code:
Dim j, lastidno As Long
Sheets("Part B + C Modules").Activate
lastidno = Range("A2", Range("A2").End(xlDown)).Count + 1
For j = 2 To lastidno
If Range("O" & j) = "" Then
Sheets("Part B + C Modules").Range("A" & j).Copy
Sheets("No Options Selected").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
ActiveSheet.Paste
Sheets("Part B + C Modules").Activate
Rows(j).EntireRow.Delete
End If
Next
MsgBox "done"
End Sub
Iteration and deleting rows goes backwards using a negative Step > For j = lastidno to 2 Step -1
However, it appears you could rewrite your code a bit more elegantly to avoid:
Implicit Range references
Iteration
Use of Activate or Select
The key is to have Explicit sheet references to work with. Also the use of SpecialCells can come in handy here to return a Range in one go (so no more iteration). This way you can also delete all rows in one go!
You code could, for example, look like:
Sub Test()
'Set up your worksheet variables
Dim ws1 As Worksheet: Set ws1 = Worksheets("Part B + C Modules")
Dim ws2 As Worksheet: Set ws2 = Worksheets("No Options Selected")
'Get last used rows
Dim lr1 As Long: lr1 = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row
Dim lr2 As Long: lr2 = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row
'Set your range and copy it
Dim rng As Range: Set rng = ws1.Range("O2:O" & lr1).SpecialCells(xlCellTypeBlanks).Offset(0, -14)
rng.Copy ws2.Cells(lr2 + 1, 1)
'Delete your range
rng.EntireRow.Delete
MsgBox "done"
End Sub
Small catch: SpecialCells will return an error when no empty cells are found. You might want to work your way around that using On error or count the empty cells in your Range first (my personal preference). So that specific part could looke like:
'Set your range and copy it
If WorksheetFunction.CountBlank(ws1.Range("O2:O" & lr1)) > 0 Then
Dim rng As Range: Set rng = ws1.Range("O2:O" & lr1).SpecialCells(xlCellTypeBlanks).Offset(0, -14)
rng.Copy ws2.Cells(lr2 + 1, 1)
End If
Another small note for future reference: Dim j, lastidno As Long only has lastidno declared as Long data type. j Variable is auto-assigned to Variant/Integer so could potentially become a problem when your data is larger than this data type can hold > Return an OverFlow error.

How to copy only visible/filtered array values to clipboard?

So I have a worksheet of data and I want to copy a comma-delimited array to my clipboard. If I have to paste the value into a cell first, that is fine as well. The worksheet has autofilters on and is filtered. I only want to select the values that are currently visible due to the filtering, not the whole array.
The array is in column P and starts in P2. I have a LastRow set up, and have been able to get the comma-delimited part to work, but am having trouble with the copying to clipboard part and the visible values only part.
The code below creates the comma-delimited list and I can show it in a message box or something, but I'm not sure how to copy it to the clipboard or how to make sure only visible values are being selected.
Dim LastRow As Long
LastRow = Range("P" & Rows.Count).End(xlUp).Row
Dim arr
arr = Join(Application.Transpose(Range("P2:P" & LastRow).Value), ",")
Try this code
Sub Test()
Dim arr, rng As Range, c As Range, n As Long
Set rng = Range("P2:P" & Cells(Rows.Count, "P").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
ReDim a(1 To rng.Cells.Count)
For Each c In rng
n = n + 1: a(n) = c.Value
Next c
arr = Join(a, ",")
End Sub
Range("P2:P" & Cells(Rows.Count, "P").End(xlUp).Row).SpecialCells(xlCellTypeVisible)

Copy data up to last used column with vba

I was successfully able to copy data up to the last used row using VBA. I am trying to do the same thing but copy data from A1 to LastColumn2. Here is the code I have put together thus far:
Sheets("Results").Select
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
Range("A1:" & LastColumn & "2").Select
Selection.Copy
The debugger highlights the third line. This is just a portion of the code - All of the variables have been dimensioned properly.
You are getting the error because LastColumn is number. You want the string equivalent of it i.e the column name. For Further Reading
Avoid the use of .Select and fully qualify your objects. INTERESTING READ
Is this what you are trying?
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Dim LastCol As Long
Dim LastColumn As String
Set ws = ThisWorkbook.Sheets("Results")
With ws
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'~~> Return column name from number
LastColumn = Split(.Cells(, LastCol).Address, "$")(1)
Set rng = .Range("A1:" & LastColumn & "2")
Debug.Print rng.Address
rng.Copy
End With
End Sub
The problem is that the range you are passing is wrong because it is wating simething like:
Range("A1:C2").Select
and you are passing:
Range("A1:32").Select
So what you can do is:
Range(cells(1,1),cells(2,lastcolumn)).Select
Cell(1,1) = A1 beacuse its is row number 1 column number 1
As mentioned it is better if you just
Range(cells(1,1),cells(lastcolumn,2)).copy
Hope it helps

Resources