Excel VBA - how to select column AND row of active cell? - excel

I have been struggling with VBA code that selects entire row and column of active cell. I tried many codes, but all of them failed. I don't want to make any changes to range, I need to just select it.
How selection after macro should look like:
Selected column and row
Last version of code I came up with, still not working. Any ideas how to achieve it or fix it?
Private Sub CommandButton7_Click()
Dim Column As range
Set Column = ActiveCell.EntireColumn
Dim Row As range
Set Row = ActiveCell.EntireRow
Dim rng As range
With ActiveSheet
Set rng = Union(.range(Column), .range(Row))
End With
rng.Select
Unload Me
End Sub

You were close, but this can done simply with:
With ActiveCell
Union(.EntireRow, .EntireColumn).Select
End With
Or just a one-liner:
Union(ActiveCell.EntireRow, ActiveCell.EntireColumn).Select

Related

Can not SUM selected cells With SUMIF

I would like to be able to Check for criteria "owners" In column A and SUM cell from the same row column E with the cell above and repeat through the spread sheet where owner is found.
I have tried to use Function =SUMIF(A3,"*owner*",E2:E3) This returns the Value above the cell in the row with owner but does not SUM them.
I have also tried this VBA CODE and it does the same thing.
Sub vba_sumif()
Dim gRange As Range
Dim sRange As Range
Set gRange = Range("A3")
Set sRange = Range("E2:E3")
Range("G2") = _
WorksheetFunction.SumIf(gRange,"*Owner*", sRange)
End Sub
Ideally it would return the summed cells in the above cell. using VBA
Thanks again,
Aaron
Well first of all, I would suggest just using the formula unless you have a reason not to:
Formula:: Your first error with the formula is both ranges need to be the same size.
VBA:: Same thing here with range sizes, then you also need to remember to make sure Excel knows what sheet you're referring to. I like to do this with a With My_Worksheet_Namestatement, then include a . before any range from that sheet. Just make sure to change the sheet name to your sheet name
Option Explicit
Sub vba_sumif()
Dim TableSheet As Worksheet
Dim gRange As Range
Dim sRange As Range
Set TableSheet = Worksheets("TableSheet")
With TableSheet
Set gRange = .Range("A2:A13")
Set sRange = .Range("E2:E13")
.Range("G2").Value = _
WorksheetFunction.SumIf(gRange, "*Owner*", sRange)
End With
End Sub

How do I reference a range 1 column to the right of a work range using a range variable?

I need to work on a range of cells that changes every day. I have decided that the best way to handle this might be to use an InputBox to get the range to work on. The macro massages the data and places it 1 column to the right of the range from the InputBox, but the data is not in adjacent cells (if that makes a difference.)
I would like to select the cells 1 column to the right of the selected range where the new data is located (this is the preferred solution) and format the new data. Or if I can't select the range, I could just select the entire column and then change the format of the entire column.
I can't figure out how to extract the range info to do the necessary math on it and then use it to change the format of the newly created data.
I have included a simplified sample of the problem area of the code.
I would appreciate your help with this.
Sub InputBox_Range_Test()
Dim rng As Range
Set rng = Application.InputBox(Prompt:=PromptString, Type:=8)
Debug.Print rng.Address
'
'*** Needs to select the range that is
'*** 1 column to the right of the input range
'
Columns(rng).Select
Selection.NumberFormat = "0.00%"
Range("I4").Select
End Sub
I finally figured it out. I was thinking about it the wrong way. I was trying to make it harder that it needed to be. I just had to use the offset property.
Here's what I came up with:
Private Sub CommandButton2_Click()
Dim rngTarget As Range
Set rngTarget = Application.InputBox(strPrompt, "Select the Range to work with", Type:=8)
Range(rngTarget.Address).Offset(, 1).Select
Selection.NumberFormat = "0.00%"
Range("P2").Select
End Sub

How to make Formula give multiple results across other cells

So I'm working on an excel sheet, and this is something i really can't figure out.
I want it to be that if the contents of a cell match certain criteria, an entire column of cells will be pasted according to that cell. The cell is a drop down with 32 different options (that can be reduced if theres no way to do it) and each option corresponds to a different column of data. The columns that have to be pasted have roughly 32 cells of data each.
My current formula is basically =IFS(A1="Potato",Sheet2!G:G) but this gives me a '0'. The best i can do is change the formula to =IFS(A1="Potato",Sheet2!G1) or =IFS(A1="Potato",Sheet2!G1:G32) but both of these formulas give me the contents of the first cell only (G1).
Any ideas on how I could get this done without having to contact aliens or build a spaceship?
You can use formulas, or VBA.
I have assumed your 32 columns of source data are in Sheet2 with the headers in row 1.
Formula Solution
In Sheet1 A73, enter:
=INDEX(Sheet2!$A$1:$AF$41,ROW(A1),MATCH($A$1,Sheet2!$A$1:$AF$1,0))
Copy this formula to Sheet1 A74:A105
VBA Solution
Put this code in the Sheet1 module;
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range
If Not Intersect(Target, Range("A1")) Is Nothing Then
Application.EnableEvents = False
With Sheet2
Set c = .Rows(1).Find(what:=Sheet1.Range("A1").Value)
If Not c Is Nothing Then
Set c = Intersect(.UsedRange, c.EntireColumn)
Sheet1.Range("A73").Resize(c.Rows.Count, 1).Delete
c.Copy Sheet1.Range("A73")
End If
End With
Application.EnableEvents = True
End If
End Sub
EDITED ANSWER: (according to comment)
We have the following layout of products
Private Sub CommandButton1_Click()
'first we check the user input
Dim u_input As String
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
u_input = LCase(Trim(ws.Range("A1").Value2))
'now we need to determine how many columns there are so we know when to stop looping
Dim lc As Long, lr As Long
lc = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' loops through all the products
For Each cell In Range(Cells(1, "F"), Cells(1, lc))
' if the product matches the input
If LCase(Trim(cell)) = u_input Then
lr = ws.Cells(ws.Rows.Count, cell.Column).End(xlUp).Row
' copy and paste the active data range to A37
ws.Range(Cells(1, cell.Column), Cells(lr, cell.Column)).Copy
Sheets("Sheet2").Range("A37").PasteSpecial
End If
Next cell
End Sub
So, upon entering cucumber and clicking the button:
We would get the following result:
You can add any number of products there, as long as the first product starts in column F. (though that can also be changed in code).
PS: This will however end up overwriting your data and also cause data to overlap if your data ranges are not the same. It probably would be smarter to paste the data into the next empty row in sheet2 instead of directly to A37
This can be achieved by changing the line
Sheets("Sheet2").Range("A37").PasteSpecial to Sheets("Sheet2").Range(Cells((Rows.Count, "A").End(xlUp).Row, "A")).PasteSpecial

Excel List of Blank Cells

So I have a big excel sheet with a bunch of empty cells in various locations. I want an easy to work with list of which cells are empty. I was hoping to make a new worksheet that was populated with the locations of the empty cells. I wanted to have this to just populate the cells I want it to. I kept the header from the worksheet I will be checking and added a blank cells count, so I want the following cells in the column to be populated by the list of empty cell locations.
Now I know I can use =ISBLANK to test if a cell is empty or not, but I only care about the cells that return TRUE. So I figure I'll need a loop. And I want the location of the cell so I can use =CELL. And to make this most readable I want to do this on a column by column basis.
But I want to populate a spreadsheet with this information in a manner similar to how functions work (I just want to copy and paste it to other cells and columns). But it's pretty clear that I am going to need VBA.
My question is how can I create a macro to populate my spreadsheet with a list of empty cells? How do I apply it to the cells?
I assume you have data in sheet1, I have used sample range// Range("A1:c15") however you can define range as per need and blank cells address will be published in next sheet.
Sub FindBlank()
Dim rng As Range
dim i as long
For Each rng In Sheet1.Range("A1:c15").SpecialCells(xlCellTypeBlanks)
i = i + 1
Sheet2.Cells(i, 1) = rng.Address
Next
End Sub
If you want a list of the cells that are empty, you can use Range().SpecialCells(xlCellTypeBlank):
Sub getEmptyCellAddresses()
Dim rng As Range
Dim ws as Worksheet
Set ws = Sheets("Sheet1") ' CHANGE AS NECESSARY
Set rng = ws.Range("A1:A15").SpecialCells(xlCellTypeBlanks) ' Edit/change range as necessary
ws.Cells(1, 2).Value = rng.Cells.Address ' Change `ws.cells(1, 2)` to whatever destination you like
End Sub
Edit: Ah, beaten by 16 seconds by #RamAnuragi ...but anyways, they're slightly different ways to tackle the question so I'll leave it.
Edit: For funsies, here's another way to put them all in a column, one row per cell...and more, per your comments.
Sub listEmptyCells()
Dim emptyAddresses() As String
Dim i As Long
Dim ws As Worksheet
Dim rng As Range
Set ws = Sheets("Sheet1") ' CHANGE AS NECESSARY
Set rng = ws.Range("A1:A15")
If WorksheetFunction.CountBlank(rng) = 0 Then
MsgBox ("No empty cells in the range")
Exit Sub
End If
emptyAddresses() = Split(rng.SpecialCells(xlCellTypeBlanks).Address, ",")
For i = LBound(emptyAddresses) To UBound(emptyAddresses)
ws.Cells(i + 1, 2).Value = emptyAddresses(i)
Next i
End Sub

Create an Excel Macros to Delete Rows based on the selected cells in a Sheet

I have created a macro however its not really working since the rows actually change during the delete. The user select any # of cells in a table. On run of the macros, just those rows which belong to the selected cells are deleted. Here is what I got to so far:
Sub DeleteSelectedRows()
Dim Cell As Range
With Sheet1
For Each Cell In Selection
.Range(Cell.Address).EntireRow.Delete
Next Cell
End With
End Sub
Any help would be greatly appreciated.
Do not use a For Each loop when modifying the collection, use a simpler For loop, starting at the last row index (or column index) and going backwards to the first index.
Make sure the loop is set to Step -1 to go backwards. The backwards direction is required because in Excel, when you delete a row/column, the remaining rows/columns move up/left, so all further indexes may be wrong after the first edit.
Dim rng as Range
Set rng = Selection
Dim firstRow as Integer
Dim lastRow as Integer
firstRow = rng.Row
lastRow = rng.Rows(rng.Rows.Count).Row
Dim i as Integer
For i = lastRow to firstRow Step -1
Call ActiveSheet.Rows(i).Delete()
Next i
In some (probably rare) cases, a user could ctrl+click to select a non-contiguous range. This code would account for that possibility, while still only deleting the rows that are actually selected:
Sub DeleteSelectedRows()
Dim rArea As Range
For Each rArea In Selection.Areas
rArea.EntireRow.Delete
Next rArea
End Sub

Resources