Select range from A1 to end of file using VBA in Excel - excel

I want to select all values in Excel 2007 worksheet between A1 and end of file (effect of ctrl End). There are always 4 columns but the rows will range from 2 to possibly hundreds. There will possibly be lots of blank cells throughout the selection, including the last cell.
The following just goes to the last cell to be selected, not the entire range. How can I modify this to accomplish what I want?
ActiveSheet.Range("A1", SpecialCells(xlLastCell)).Select
Many thanks.

You almost have it. The SpecialCells method needs a qualifier:
ActiveSheet.Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select

If you always want the first four columns, then perhaps:
Sub dural()
Intersect(ActiveSheet.UsedRange, Range("A:D")).Select
End Sub

Record a macro doing it then review the code:
Something like this may work.
Range("A1").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Running this macro selected the below in my example:

Related

Using XlDown and select a defined column range

I have this code that is using xlDown to determine the last row of data (minus 1) but I need to go to a defined column. So the selection would be as follows:
Go to A6 then do an xlDown -1
Then select the resulting row from xlDown and combine it with column BU
As an example, if the result from the xlDown is row 89 then the range to select should be A6:BU89
I tried using the xlRight but the data is inconsistent and can have blank columns in different places but I always want to go to column BU.
I can't seem to get it right, can someone help me out?
Sub AAPrepare_Pipeline_Data()
Range("A6").Select
Range(Selection, Selection.End(xlDown).Offset(-1)).Select
'Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
End Sub
Use the same code to gain the cells in column A but Resize the columns to 73 columns wide before the Select or Copy command.
Sub AAPrepare_Pipeline_Data()
Range(Range("A6"), Range("A6").End(xlDown).Offset(-1)).Resize(, 73).Copy
End Sub
You don't need to Select something in order to reference or copy it.
You can get the row number you desire, use it to create the range, and then select that range. Something like this should work:
Sub AAPrepare_Pipeline_Data()
Range("A6").Select
Dim desiredRow As Integer
desiredRow = Selection.End(xlDown).Offset(-1).Row
Range("A6:BU" & desiredRow).Select
Selection.Copy
End Sub

Check a condition and bring a value from all the sheets of a file

I´ve a file with about 50 tabs, and each with a variable name.
Each tab includes a standard form (15 columns, 1000 or more rows).
I need to check each row:
If column D has a non-null value and column B is greater than some other value, I need to bring the value of column A in a different tab.
I´ve to admit I thought this would be simple but I can´t find a way to make it work.
Any advise would be much appreciated!
Based on the detail you've provided, my understanding is that in every worksheet you want to bring forward some value from a base tab. Thus, the following formula would work:
=IF(D2>0,IF(B2>100,Sheet2!A2,"2nd False"),"1st False")
As you copy this down across rows, it will fetch the corresponding value on the same row in another sheet, which as far as I can see is what you're after. If it isn't, then yes you would need to bring in a vlookup.
In terms of automation, either highlight all your tabs or record a macro with the following steps:
Sub Macro2()
'
' Macro2 Macro
'
' Keyboard Shortcut: Ctrl+Shift+G
'
Range("E2").Select
Selection.Copy
ActiveSheet.Next.Select
Range("E2").Select
ActiveSheet.Paste
Selection.AutoFill Destination:=Range("L2:L288")
Range("E2:E288").Select
Range("E2").Select
Application.Run "'Your File.xlsx'!Macro2"
End Sub
Hope that is what you're after and good luck

Excel VBA: Replace Range('Cell).Select with an If Statement

I am using Excel Visual Basic for Applications (VBA)
I have a Macro that is selecting a set of cells, cutting them and pasting them into a defined cell in another sheet that the user selects. However, I need to have the macro look for empty rows (represented as a 0) in the user-chosen spreadsheet, as data may already be in the spot where it is getting pasted.
My Code:
Sub Button11_Click()
'
' Button11_Click Macro
'
'
Range("A2:K2").Select
Selection.Cut
Sheets(Application.InputBox("Type desired Team")).Select
Range("B4").Select
Sheets("ImporterSheet").Select
End Sub
Basically,
Range(B4).Select
needs to be replaced with
Range(If ActiveCell <> 0 then ActiveCell.Offset(1,0). If ActiveCell = 0 then paste data here)
Try this:
Range(Range("B:B").Find(0, [B1]).Address).Select
It selects the first cell with 0 in it in Column B.
Is this what you need?
BTW, try going through THIS which is definitely a good read to improve your coding.

How to select clear table contents without destroying the table?

I have a vba function in excel 2010 that I built using help from people on here. This function copies the contents of a table/form, sorts them, and sends them to the appropriate tables.
Now after running this function I want the original table to be cleared. I can achieve this with the following code, assuming ACell has been defined as the first cell in the table.
ACell.ListObject.Range.ClearContents works fine, the only problem is it deletes the table as well as the data values.
Is there any way around this? I would rather not have to set the table up every time I enter some data.
How about:
ACell.ListObject.DataBodyRange.Rows.Delete
That will keep your table structure and headings, but clear all the data and rows.
EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:
With loSource
.Range.AutoFilter
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With
If you want to leave all the rows intact with their formulas and whatnot, just do:
With loSource
.Range.AutoFilter
.DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With
Which is close to what #Readify suggested, except it won't clear formulas.
Try just clearing the data (not the entire table including headers):
ACell.ListObject.DataBodyRange.ClearContents
I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.
Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
With lst
If .ShowAutoFilter Then .AutoFilter.ShowAllData
On Error Resume Next
With .DataBodyRange
.Offset(1).Rows.Clear
.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
End With
On Error GoTo 0
.Resize .Range.Rows("1:2")
End With
End Sub
There is a condition that most of these solutions do not address. I revised Patrick Honorez's solution to handle it. I felt I had to share this because I was pulling my hair out when the original function was occasionally clearing more data that I expected.
The situation happens when the table only has one column and the .SpecialCells(xlCellTypeConstants).ClearContents attempts to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table that only has one column) and the SpecialCells command applies to the entire sheet instead of the selected range. What was happening to me was other cells on the sheet that were outside of my table were also getting cleared.
I did some digging and found this advice from Mathieu Guindon:
Range SpecialCells ClearContents clears whole sheet
Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
If the list/table only has one column (in row 1), this revision will check to see if the cell has a formula and if not, it will only clear the contents of that one cell.
Public Sub ClearList(lst As ListObject)
'Clears a listObject while leaving 1 empty row + formula
' https://stackoverflow.com/a/53856079/1898524
'
'With special help from this post to handle a single column table.
' Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
' Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead
On Error Resume Next
With lst
'.Range.Worksheet.Activate ' Enable this if you are debugging
If .ShowAutoFilter Then .AutoFilter.ShowAllData
If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear
.DataBodyRange.Offset(1).Rows.Clear
If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell.
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ElseIf Not .Range.HasFormula Then
' Only one cell in range and it does not contain a formula.
.DataBodyRange.Rows(1).ClearContents
End If
.Resize .Range.Rows("1:2")
.HeaderRowRange.Offset(1).Select
' Reset used range on the sheet
Dim X
X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73
End With
End Sub
A final step I included is a tip that is attributed to John Walkenbach, sometimes noted as J-Walkenbach tip 73 Automatically Resetting The Last Cell
I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.
Sub CleanTheTable()
Application.ScreenUpdating = False
Sheets("Data").Select
ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
'Remove the filters if one exists.
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
'Clear all lines but the first one in the table leaving formulas for the next go round.
With Worksheets("Data").ListObjects("TestTable")
.Range.AutoFilter
On Error Resume Next
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ActiveWindow.SmallScroll Down:=-10000
End With
Application.ScreenUpdating = True
End Sub
I usually use something very simple if you just want to clear table contents.
Sub Clear_table()
Range("Table1").ClearContents
End Sub
Obviously if you have a workbook with multiple pages you might want to change the code to accommodate that.
Sub Clear_table()
Worksheets("Sheet1").Range("Table1").ClearContents
End Sub
If you want to delete the entire table except your headers, and your formula, you can try this:
Sub DeteteTableExceptFormula()
Dim tb As ListObject
Set tb = activeworksheet.ListObjects("MyTable")
tb.DataBodyRange.Delete
End Sub

Last cell selection .End(xlup) using VBA in Excel 2003 'lists' - requires two .Select to get correct cell?

I'm a new convert from Experts-Exchange since I noticed they increased the 'Free Premium Services' points threshold.
It seems that Excel 2003 has issues with the End(xlup) command when using it in a worksheet that contains an Excel 'List'.. If I select a cell outside the 'list' boundary, and then try to select the last cell in the worksheet by using VBA, I have to call the .Select function twice to make sure I am getting the correct cell. If the original cell is inside the 'list' boundary then i only need one .Select. My hacked together solution is below, with two selects, as I can never be sure what cell may be selected on save. I include a version check at open to run different code in Excel 2007 (this code fails in 2007, where the .End(xlUp) command works properly).
Is there a more eloquent way to handle this?
Thanks for any help!
.Range("A1").Select
.Cells(.Rows.Count, "A").End(xlUp).Select
.Cells(.Rows.Count, "A").End(xlUp).Select
'two .Selects needed to select correct cell in Excel 2003 list because original selection (A1) was not in list'
.Range("A1").Select
.Cells(.Rows.Count, "T").End(xlUp)(-2, 1).Select
.Cells(.Rows.Count, "T").End(xlUp)(-2, 1).Select
'two .Selects needed to select correct cell in Excel 2003 list because original selection (A1) was not in list'
.Cells(.Rows.Count, "T").End(xlUp)(-3, 1).Select
'only one select needed here because original selection above was within the list'
See how this does:
Sub Example()
Dim rngLstCell As Excel.Range
Set rngLstCell = GetLastCell(Excel.Worksheets("Sheet1"))
MsgBox "The last cell is: " & rngLstCell.Address, vbInformation
End Sub
Public Function GetLastCell(ByVal ws As Excel.Worksheet) As Excel.Range
Dim rngRtnVal As Excel.Range
With ws.UsedRange
Set rngRtnVal = .Find("*", .Cells(1, 1), , , xlByRows, xlPrevious)
If rngRtnVal Is Nothing Then
Set rngRtnVal = .Cells(1, 1)
End If
End With
Set GetLastCell = rngRtnVal
End Function
Using find may seem weird at first but it ends up being the most reliable way due to some vagaries in the way empty cells are handled.
This may not be perfect if your data is non-normalized (jagged).
I found that my use of .End(xlUp).Select prior to acting on the .End(xlUp) cell was causing the problem. If I simply avoid the .End(xlUp).Select prior to operating on the .End(xlUp) cell, the problem is less complex. It can be easily solved by preceding any .End(xlUp) operation with .Range("A1").Select. See the code for explanation. This doesn't really fix the problem with improper .End(xlUp) cell 'selection' - but I'm not interested in 'selecting' the cells, just operating on them. I must mention that I use .Range("A1").Select because A1 is outside of the 'list' that I'm manipulating via VBA.
'commented out - just need to add a ".Range("A1").Select" prior to any .End(xlUp) usage (besides .End(xlUp).Select) to make it work in Excel 03
'.Range("A1").Select
'.Cells(.Rows.Count, "A").End(xlUp)(0, 1).Select
'.Cells(.Rows.Count, "A").End(xlUp)(0, 1).Select
''two .Selects needed to select correct cell in Excel 2003 'Lists'
'Set EntryDate = Cells(.Rows.Count, "A").End(xlUp)(0, 1) 'no need to select cell first, then operate on it, as in the code above
'fixed code below
.Range("A1").Select 'needed for Excel 03 to select correct cell
Set EntryDate = Cells(.Rows.Count, "A").End(xlUp) 'just operate on the cell instead of selecting it first
Are you sure the ranges that you were working with were identical? You shouldn't get different results using the End property in Excel 2007 versus 2003.
Looking at your code:
.Range("A1").Select
.Cells(.Rows.Count, "A").End(xlUp).Select
.Cells(.Rows.Count, "A").End(xlUp).Select
Each of these lines of code have exactly zero impact on one another. No honest explanation can be offered about why the End property is giving you different results based on the code you've provided. From what's written, you should get the same results each time. (That's assuming you're working with identical ranges.) I'd be suspicious of any other code that's being executed. I can offer a couple general tips though: If you use End starting with a blank cell, it will stop at the first non-blank cell. If you start with a non-blank cell, the opposite is true. Looking at the screenshot below:
Range("B13").End(xlUp).Select 'selects B12
Range("B12").End(xlUp).Select 'selects B2
Range("A12").End(xlUp).Select 'selects A6
So whether or not your list is contiguous is an issue. Also, it is not necessary to select a range before you do something to it. Telling Excel to select cell A1 does not impact how it executes .Cells(.Rows.Count, "A").End(xlUp).Select. Assuming that line is within a With block that refers to a worksheet, that line of code is the same thing as navigating to cell A65536 (or A1048576 in Excel 2007) and pressing Ctrl + Up. Assuming that cell is blank, Excel will navigate upwards until it finds the first non-blank cell in column A. If your With block refers to a range object, then that line of code will go to the first column, bottom row of that range and navigate upwards until it comes to the first blank or non-blank cell.

Resources