Selecting entire column with blank cells with alternate empty cells - excel

I want to select the entire column that contain the names to copy it knowing that the Name column number can change between a spreadsheet and another and there is some blank cells in the middle (missing value)
Suppose that the Names column is the column B, so if I want to select the entire column even with the some blank cells in the middle I can use the following code:
Range("B2", Range("B" & Rows.Count).End(xlup)).Select
But the Name column number is variable. so i tried to make it like this :
Sub ColSelection ()
Dim NameHeader As range
'To select the header of Name column
Set NameHeader = ActiveSheet.UsedRange.Find("Name")
ActiveSheet.Range(NameHeader.Offset(1,0), Range(NameHeader & Rows.Count).End(xlUp)).select
' run tim error 1004 " Methode 'Range' of object '_Global' Failed
End sub
I guess that I have to replace the second NameHeader with his column address. how to do that? Should I set a Var to store the address of the range NameHeader, and use it. If it's the case how should I set this var, I mean as long or as Variant..ect?
Thanks :)

Is this what you are trying? I have commented the code so you should not have a problem understanding it. But if you still do then post your query.
Is this what you are trying?
Sub ColSelection()
Dim NameHeader As Range
Dim ws As Worksheet
Dim ColName As String
Dim LRow As Long
Dim rng As Range
Set ws = Sheet1 '<~~ Change as applicable
With ws
Set NameHeader = .UsedRange.Find("Name")
'~~> Check if we found the text
If Not NameHeader Is Nothing Then
'~~> Get the Column Name
ColName = Split(Cells(, NameHeader.Column).Address, "$")(1)
'~~> Get the last row in that range
LRow = .Range(ColName & .Rows.Count).End(xlUp).Row
'~~> Construct your range
Set rng = .Range(ColName & NameHeader.Row & ":" & ColName & LRow)
With rng
MsgBox .Address
'~~> Do whatever you want with the range
End With
End If
End With
End Sub
Screenshot
Unable to upload an image, Imgur is rejecting images for the time being. Will update it directly later.
http://prntscr.com/kftsad

No need to look at NameHeader.Address - just use its .Column - something like this (noting that you don't have to Select a Range before copying.
Sub GrabNameCol()
Dim NameHeader As Range
Set NameHeader = ActiveSheet.UsedRange.Find("Name")
If Not NameHeader Is Nothing Then
ActiveSheet.Range(NameHeader.Offset(1), Cells(Rows.Count, NameHeader.Column).End(xlUp)).Select ' or just .Copy
End If
End Sub

Sub test1a()
Dim NameHeader As Range
Set NameHeader = ActiveSheet.UsedRange.Find(InputBox("HEADER"))
If Not NameHeader Is Nothing Then
ActiveSheet.Range(NameHeader.Offset(1), Cells(Rows.Count, NameHeader.Column).End(xlUp)).Select
End If
End Sub

Related

VBA Selecting a a range for a combobox input

I'm attempting to set the values shown in a combo box to the data shown in a single column of a filtered list so that it can be changed as required. Im running into error 1004 Application-defined object error when using a variable to define the range for the list items however.
the code i've written is:
Sub Vehicle_Catergory()
Dim LastRow As String
LastRow = Sheets("Vehicle_Data").Range("B2").End(xlDown).Address
Sheets("marine Vehicle Selection").ListBox_Vehicle_selection.Clear
'MsgBox LastRow.Address
'Filters vehicle Data for vehicle Types
Dim Criteria_1 As Range
'selects the criteria
Set Criteria_1 = Sheets("Config").Range("A3")
'copies the filtered data to the destination
With Sheets("Vehicle_data").Range("A2")
.AutoFilter field:=1, Criteria1:=Criteria_1
End With
Sheets("marine Vehicle Selection").ListBox_Vehicle_selection.List = Sheets("Vehicle_Data").Range("B3:LastRow").SpecialCells(xlCellTypeVisible).Value
End Sub
the error occurs in the last line, at the LastRow variable, it works when replaced with a cell address but i need it to be able to vary with a changing list length.
I have also tried setting lastRow to a range and using LastRow.adress to no avail and the same error
Could you test this?
Sub Vehicle_Catergory()
Dim LastRow As Range
LastRow = Sheets("Vehicle_Data").Range("B2").End(xlDown).Address
Sheets("marine Vehicle Selection").ListBox_Vehicle_selection.Clear
Sheets("Vehicle_Data").Range("B2").Select
Selection.End(xlDown).Select
Set LastRow = Selection
'Filters vehicle Data for vehicle Types
Dim Criteria_1 As Range
'selects the criteria
Set Criteria_1 = Sheets("Config").Range("A3")
'copies the filtered data to the destination
With Sheets("Vehicle_data").Range("A2")
.AutoFilter field:=1, Criteria1:=Criteria_1
End With
Sheets("marine Vehicle Selection").ListBox_Vehicle_selection.List = Sheets("Vehicle_Data").Range("B3:" & LastRow.Address).SpecialCells(xlCellTypeVisible).Value
End Sub
A range needs Column and row for both start and end:
Sheets("marine Vehicle Selection").ListBox_Vehicle_selection.List = Sheets("Vehicle_Data").Range("B3:B" & LastRow).SpecialCells(xlCellTypeVisible).Value
Also, try this method of lastrow, this should work better with some cells being empty and thus giving you a false value of lastrow:
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Vehicle_Data") 'or declare Dim wb As Workbook and set it to what you need with ws then as Set ws = wb.Sheets("Vehicle_Data")
'or just skip the ws and use the Range immediately if your code is only used here
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
Hope that helps :)

Find text in one column, if true then match the text in the column next to it with a column on a separate sheet and insert a formula

Here's what I have:
Response Flow
I have one sheet called Response Flow that has Response, Y/N and a Total. If the Response has a Y next to it I want to match the Response Name with the Response Name on Sheet 2 ("Campaigns") and insert a formula in the column next to the response name on Sheet 2 using VBA code. Below is what I have so far.
Sub Volume_Calc()
Dim LastRowR As Long
Dim LastRowC As Long
Dim LastRowI As Long
Dim LastRowA As Long
Dim rngFoundCell As Range
Dim cell As Range
Dim text As String
Dim FindRow As Range
LastRowR = Range("C65536").End(xlUp).Row
LastRowC = Range("K65536").End(xlUp).Row
LastRowI = Range("I65536").End(xlUp).Row
LastRowA = Range("A65536").End(xlUp).Row
Set FindRow = Worksheets("ResponseFlow").Range("C:C").Find(What:="Y",
LookIn:=xlValues)
Do While FindRow = True
If Application.Match(Worksheets("Campaigns").Range("K6"),
Worksheets("ResponseFlow").Range("A4:A" & LastRowA), 0) Then
Worksheets("Campaigns").Range("I6:I" & LastRowI).Formula = "=INDEX(ResponseFlow!$B$3:$B$145,MATCH(Campaigns!$K6,ResponseFlow!$A$3:$A$145,0))"
End If
Loop
End Sub
What you're intending to do seems like it'd be easier to do in Excel without VBA, but if you insist on having some macro insert formulas, this might be an easy approach. First put the dynamic formula you want to be pasting in to the right of the columns with a Y/N, SOMEWHERE in your sheet. In my example below I used Cell("Z1"). Make sure it's dynamic so that if you were to copy/paste formula into another cell, it would adjust correctly.
Again make sure whatever dynamic match formula you want to the right of your values is somewhere and configured to be dynamic. In my example it's on Response ws in cell Z1.
Sub Volume_Calc()
Dim Resp_WS As Worksheet: Set Resp_WS = Worksheets("ResponseFlow")
Dim CAMP_WS As Worksheet: Set CAMP_WS = Worksheets("Campaigns")
Dim rCell As Range
Dim cCell As Range
'Loops through Response Sheeet column "C" looking for values of "Y"
For Each rCell In Intersect(Resp_WS.Range("C:C"), WResp_WS.UsedRange).Cells
If UCase(rCell.Value) = "Y" Then
'When finds a cell with Y, it then loops through Campaigns Sheet column "I"
'looking for a value that matches one column to the left where the "Y" was found
For Each cCell In Intersect(CAMP_WS.UsedRange, CAMP_WS.Range("I:I")).Cells
'When match is found, the macro will insert the formula to the right
'of the cell in Campaigns, with the dynamically updated formula in cell Z1
If cCell.Value = rCell.offset(0,-1).Value Then
cCell.Offset(0, 1).FormulaR1C1 = Resp_WS.Range("Z1").FormulaR1C1
End If
Next cCell
End If
Next rCell
End Sub

Loop through range and find empty cells

I have a problem with the following code. I would like it to loop through a range (AK2 until end of data) and then any time it finds an empty cell it changes its value to Account receivable. Its not doing it, I also dont get any error notification. My guess is that I´m doing something wrong with setting the variables:
Option Explicit
Private Sub Leere()
Dim rng As range
Dim rcell As range
Dim WS As Worksheet
Set WS = Worksheets("Sheet2")
Set rng = WS.range("AK2", range("AK2").End(xlDown))
For Each rcell In rng
If rcell.Value = " " Then
rcell.Value = "Accounts Receivable"
End If
Next
End Sub
Any ideas?
use SpecialCells()
With ws
.Range("AK2", .Cells(.Rows.Count, "AK").End(xlUp)).SpecialCells(XlCellType.xlCellTypeBlanks).Value = "Accounts Receivable"
End With
You should be able to replace the empty (no formula) cells with something like this:
Set ws = ThisWorkbook.Worksheets("Sheet2")
Set rng = ws.Range("AK2", ws.Cells(ws.Rows.Count, "AK").End(xlUp))
rng.Replace "", "Accounts Receivable", xlWhole
Another non-VBA option can be Conditional Formatting for blank cells. The cell values will still be blank, but the displayed text change will be dynamic.

Look for first cell with certain value in column, then insert 3 rows above

I work on a spreadsheet every morning and need to automate the following in a VBA macro:
In column AE, look for first value greater than zero, then insert 3 rows above the row containing that specific cell.
Something like this should work for you:
Sub tgr()
Dim ws As Worksheet
Dim lRow As Long
Set ws = ActiveSheet 'Adjust to be the correct worksheet if necessary
With Intersect(ws.UsedRange, ws.Columns("AE"))
On Error Resume Next
lRow = Evaluate("=MATCH(1,INDEX((ISNUMBER(" & .Address(External:=True) & "))*(" & .Address(External:=True) & ">0),),0)")
On Error GoTo 0
End With
If lRow > 0 Then
ws.Rows(lRow).Resize(3).Insert
Else
MsgBox "No values in column AE found to be greater than 0."
End If
End Sub

Formula auditing - error checking for a specific region

I would like to ask whether it is possible to check inconsistent formula for a specific region.
In my case, col D and col E contain different sets of formula.
I just want to ensure that all formula in col E are consistent.
Is it possible to do so??
Here is one way.
Let's say your worksheet looks like this
Now Paste this code in a module and run it. It will tell you which cells have inconsistent formulas. See below screenshot
I have commented the code so that you will not have any problem understanding it. If you do simply ask :)
Option Explicit
Sub GetInConsCells()
Dim ws As Worksheet
Dim rng As Range, cl As Range, errCells As Range
Dim ErrorCells As String
Dim lRow As Long
'~~> Create a temp copy of the sheet
ThisWorkbook.Sheets("Sheet1").Copy After:=Sheets(ThisWorkbook.Sheets.Count)
Set ws = ActiveSheet
With ws
'~~> Clear Col D and Col F Contents
.Range("D:D,F:F").ClearContents
'~~> Find the last row of col E
lRow = .Range("E" & .Rows.Count).End(xlUp).Row
'~~> Set your range
Set rng = Range("E1:E" & lRow)
'~~> Check if the cells have inconsistent formulas
For Each cl In rng
If cl.Errors(xlInconsistentFormula).Value Then
If errCells Is Nothing Then
Set errCells = cl
Else
Set errCells = Union(cl, errCells)
End If
End If
Next cl
'~~> Display relevant message
If Not errCells Is Nothing Then
ErrorCells = errCells.Address
MsgBox "Formulas in cells " & ErrorCells & " are inconsitent"
Else
MsgBox "All Formulas are consistent"
End If
End With
'~~> Delete temp sheet
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End Sub
A quick and pragmatic way would be to use another column (temporarily):
Assuming you want to check that each cell in column E has the formula =SUM(A1:D1), simply enter the formula =(SUM(A1:D1)-E1 in another column. Then select the column and filter for FALSE- this will give you all the formulas that have different results!

Resources