How to select and paste values in filtered cells in Excel using VBA - vba

Please see below picture in which a filter is applied in column a to choose Item "b" and then updated "OK" in comment field. Do you have any idea how this can be done through macro? Also, I need to know how to select the visible cells in a column when a filter is on and filtered.

Sub Copy_Filtered_Cells()
Set from = Application.InputBox("Select range of Cell to copy", Type:=8).SpecialCells(xlCellTypeVisible)
'Selection.SpecialCells(xlCellTypeVisible).Select
'Set from = Selection
Set too = Application.InputBox("Select range to Paste Copied Cells", Type:=8)
For Each Cell In from
Cell.Copy
For Each thing In too
If thing.EntireRow.RowHeight > 0 Then
thing.PasteSpecial
Set too = thing.Offset(1).Resize(too.Rows.Count)
Exit For
End If
Next
Next
End Sub
it might work for you.

Related

VBA check for empty cells in column and print value

In column J there are empty rows and rows with a value such as checked.
I have tried to write VBA code that prints "unchecked" where there is an empty cell AND this works, but when it hits a cell with a value (checked) it stops. And it won't go down to the next cell probably because I have formulas in the cell that prints nothing if not fullfilled, but it still contains that formula. In my case I have empty cells until J7 and then it starts again at J15. But this can change from time to time regarding source data.
The reason I want to do it like this is because I have a formula in column J that already have printed some values and then some VBA code that checks for other values in a different column and prints to column J. Column J is the filter master column sort of. So this is the way I have to do it I guess.
My code right now is,
Sub DoIfNotEmpty()
Dim ra As Range, re As Range
With ThisWorkbook.Worksheets("Sheet1")
Set ra = .Range("J:j25")
For Each re In ra
If IsEmpty(re.Value) Then
re.Value = "unchecked"
End If
Next re
End With
End Sub
Can I print to empty cells if the cell contains a formula which in this case has an if statement that is not filled?
Except from #Maxime Porté's points out that it should be .Range("J1:j25"). I guess the cells only look empty, but they are not.
A cell that contains an empty string, "", is not empty anymore, but it looks like it. You can test it like this:
In a new worksheet write in A1: ="" (there is no space in between!)
Copy A1 and special paste values in A1. A1 now looks to be empty.
Run Debug.Print IsEmpty(Range("A1").Value) in VBA and you get a FALSE.
The cell A1 is not empty any more, because it contains an empty string.
What can you do?
Sub DoIfNotEmpty()
Dim ra As Range, re As Range
With ThisWorkbook.Worksheets("Sheet1")
Set ra = .Range("J1:J25")
For Each re In ra
If IsEmpty(re.Value) or re.Value = vbNullString Then
re.Value = "unchecked"
End If
Next re
End With
End Sub
This will mark pseudo empty cells as "unchecked" too. But be aware that it also kills formulas that result in an empty string, "".
You could exploit the Specialcells() method of Range object:
Sub DoIfNotEmpty()
ThisWorkbook.Worksheets("Sheet1").Range("J1:J25").SpecialCells(xlCellTypeBlanks).Value = "unchecked"
End Sub
Or, if you have formulas returning blanks, then AutoFilter() "blank" cells and write in them
Sub DoIfNotEmpty()
With ThisWorkbook.Worksheets("Sheeet1").Range("J1:J25") '<--| reference your range (first row must be a "header")
.AutoFilter Field:=1, Criteria1:="" '<--| filter its empty cells
If Application.WorksheetFunction.Subtotal(103, .cells) > 1 Then .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Value = "unchecked" '<--| if any cell filtered other than headers then write "unchecked" in them
.Parent.AutoFilterMode = False
End With
End Sub

"Runtime Error '1004'" Command cannot be used on multiple selections

I put together a VBA code to take the values off a form on one worksheet and insert them into another worksheet without the blank cells inbetween, then clear the original form.
However, I run into the error "Runtime Error 1004: Command cannot be used on multiple selections" and cannot figure out what is causing it. After a little research, it seems that saving and reopening the workbook makes this error go away, but not always.
Any ideas?
Sub DataEntry()
'--- Find rows that contain any value in column G or H and copy them
Dim cell As Range
Dim selectRange As Range
For Each cell In ActiveSheet.Range("G3:H90")
If (cell.Value <> "") Then
If selectRange Is Nothing Then
Set selectRange = cell
Else
Set selectRange = Union(cell, selectRange)
End If
End If
Next cell
selectRange.EntireRow.Select
selectRange.EntireRow.Copy
'Paste copied selection to the worksheet 'Data' on the next blank row
Sheets("Data").Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial _
Paste:=xlPasteValues
'Delete content of rows after copy and paste
Union(Range("G3:G150"), Range("H3:H150")).ClearContents
The problem seems to be that the EntireRow property is becoming a variant and not a range. I initially tried to fix this by just declaring a variable as a Range, but this didn't work either. However, by doing the original Union on rows instead of cells, I was able to get this to work.
Sub DataEntry()
'Find rows that contain any value in column G or H and copy them
Dim cell As Range
Dim selectRange As Range
Dim rowRange As Range
For Each cell In ActiveSheet.Range("G3:H90")
If (cell.Value <> "") Then
If selectRange Is Nothing Then
Set selectRange = cell.EntireRow
Else
Set selectRange = Union(cell.EntireRow, selectRange)
End If
End If
Next cell
'No need to select anything here, just copy.
selectRange.Copy
.....
I'm not entirely sure why this is happening, but this fixed it for me.
EDITED because the original fix did not work.

VBA Userform dropdown menu execution

I currently have this code which allows me to launch the userform, input the an item in the text box, auto populate the date, and select from a drop down menu
then paste that information into a new row.
The cbm (combo-box) item draws its values from a separate dynamically expanding table and is a drop down menu on the userform. The date is auto populated based on todays date and the text box is draws its value from whatever the user enters.
Private Sub btnSubmit_Click()
Dim ssheet As Worksheet
Set ssheet = ThisWorkbook.Sheets("InputSheet")
nr = ssheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
ssheet.Cells(nr, 3) = CDate(Me.tbDate)
ssheet.Cells(nr, 2) = Me.cmblistitem
ssheet.Cells(nr, 1) = Me.tbTicker
My goal here is, depending on what list item is selected I want the name of that item to be pasted in a column that corresponds to that item. i.e if the user selects "apples" and the 3rd column is the "apple" column, I want it to paste in that location.
I am assuming this has to be down with some type of "if" statement.
Any help is appreciated.
Here is pic of my worksheet
supposing I correctly made my guessings, try this code
Option Explicit
Private Sub btnSubmit_Click()
Dim f As Range
If Me.cmblistitem.ListIndex = -1 Then Exit Sub '<--| exit if no itemlist has been selected
If Len(Me.tbTicker) = 0 Then Exit Sub '<--| exit if no item has been input
With ThisWorkbook.Sheets("InputSheet")
Set f = .Rows(1).Find(what:=Me.cmblistitem.Value, lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False) '<--| look for proper column header
If f Is Nothing Then Exit Sub '<--| if no header found then exit
With .Cells(.Cells(Rows.Count, "A").End(xlUp).Row + 1, f.Column) '<--| refer to header column cell corresponding to the first empty one in column "A"
.Resize(, 3) = Array(Me.tbTicker.Value, Me.cmblistitem.Value, CDate(Me.tbDate)) '<--| write in one shot
End With
End With
End Sub
it's commented so you can easily change columns references as per your needs
BTW as for the combobox filling you may want to adopt the following code:
Dim cell As Range
With Me
For Each cell In [myName]
.cmblistitem.AddItem cell
Next cell
End With
which is optimized having referenced Me once before entering the loop so that it's being kept throughout it without further memory accesses

Find If cell matches in another sheet and count/sum instances

I have been using simple excel array formulas to count certain values on a master sheet but now at the point where I have too many formulas in my document and excel is crashing.
Therefore, I would like to create a macro that can do the same task. I would like to have the code do the following:
IF the activecell in Sheet1 matches to any cell in a column(or range) in Sheet2,
AND IF the cell in the same row in an adjacent column in Sheet2 is not blank,
THEN count all the instances that specific string appears in Sheet2 column A
AND place the value 2 columns to the right of the original active cell in Sheet1.
Here is the original array formula I was using:
=SUM(IF(Sheet1!$A8=Sheet2!$A:$A,IF(SalesF_SignUp_data!$C:$C>1,1,0)))
The formula above is taking the cell A8 in Sheet1 and checking if it matches to any cell in Sheet2 column A,
AND making sure that column C in Sheet2 is not blank in the same row.
If this is TRUE then "add 1" for all the instances
AND place that value in Sheet1.
I believe the best way to do this is a For Next Loop but haven't been able to execute any successful code based on examples I've found.
Im happy to explain further if needed. Since I dont have a reputation of 10 I cant attach images but am willing to send if needed.
This is set up to run for all the cells you've selected in column A of sheet 1.
It looks in Sheet2 column A for the value on Sheet1 column A, then in Sheet1 column B, displays how many times the value appeared in Sheet2 column A along with a value in the same row of column C.
If the answer is helpful, please mark it as such. :-)
Option Explicit
Sub countinstances()
Dim result, counter, loopcount, tocomplete, completed As Integer
Dim findtext As Variant
Dim cell, foundcell, nextcell As Range
'Checks to make sure the sub isn't accidentally run on an invalid range
If ActiveSheet.Name <> "Sheet1" Or ActiveCell.Column <> 1 Or Selection.Columns.Count > 1 Then
MsgBox ("Please select a range in column A of Sheet 1.")
Exit Sub
End If
'In case of selecting the entire column A, curtail the number of blank cells it runs on.
tocomplete = Application.WorksheetFunction.CountA(Selection)
completed = 0
'For each cell in the selected range, searches Sheet2, Column A for the value in the selected cell
For Each cell In Selection
If completed = tocomplete Then Exit Sub
If cell.Value <> "" Then completed = completed + 1
findtext = cell.Value
result = 0
Set foundcell = Sheets("Sheet2").Range("A1")
'Uses the count function to determine how many instances of the target value to search for and check
loopcount = Application.WorksheetFunction.CountIf(Sheets("Sheet2").Range("A:A"), findtext)
'Skips the loop if the target value doesn't exist in column A
If loopcount = 0 Then GoTo NotFound
'For each time the target value was found, check the cell in column C. If it's not blank, increment "result"
For counter = 1 To loopcount
Set nextcell = Sheets("Sheet2").Range("A:A").Find(what:=findtext, lookat:=xlWhole, after:=foundcell)
If nextcell.Offset(0, 2).Value <> "" Then
result = result + 1
End If
Set foundcell = nextcell
Next
'Put the result in column B of Sheet1
NotFound:
cell.Offset(0, 1).Value = result
Blanks:
Next
End Sub

Select Cells With Empty Value

I'm creating a VBA script to color up some specifics cells, so far its going well, but now I need it to color some cells that have an empty value. These cells aren't blanks, they have formulas, but sometimes that formula will return "" as value. I need to select these specific cells, how can I do that?
Once again, these cells aren't empty or blank, only their value is null.
Not sure if that's what you want:
IsEmpty(ActiveCell) Checks if the cell is completely empty. No Formula or data whatsoever.
ActiveCell.Value="" Checks if the result of the cell is blank. (Blank data can be returned by a formula in the cell)
So if you want to check if the cell value is blank but there is a formula would be Not IsEmpty(ActiveCell) And ActiveCell.Value = ""
EDIT
Following clarification in comment the code would be:
Sub SelectEmpty()
Dim MyRange As Range
Dim Cell As Range
For Each Cell In Range("B18:H18")
If Cell.Value = "" Then
If MyRange Is Nothing Then
Set MyRange = Cell
Else
Set MyRange = Application.Union(MyRange, Cell)
End If
End If
Next Cell
MyRange.Select
End Sub
You can change the color of those cells, empty or "" with Conditional Formatting.
Insert a new rule, choose the option
Use a formula to determine wich values to format
And then write the formula:
=TRIM(B18)=""