Counting Records/Rows - vba

I have a macro that saves an excel file down to .txt. I need to insert a record count to the top of the .txt file ("Records|123"). I have the row inserted, I have the word Records in A1, now I'm trying to figure out how to get a row count in B1. I've tried CountIf, LastRow, EndRow and now COUNT. I'm subtracting 2 because row 1 is the record count and row 2 is column headers, and I'm referencing column D because columns A-C contain numbers and it didn't like that either. Here is what I have:
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.FormulaR1C1 = "Records"
Range("B1").Select
ActiveCell.Value = (EndRow - 2)
ActiveCell.FormulaR1C1 = "=COUNT(D:D)"
This is giving me Records|0. Does anyone have any ideas on how to get this to work? Or can you point me in a different direction? Thank you in advance.

Something like this.
Dim ws As Worksheet
Dim lr As Long
ws = ThisWorkbook.Sheets("Sheet1")
lr = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
With ws
.Range("B1") = lr - 2
End with

You could have just gotten a row count before you inserted the header row.
dim newvariable as long
newvariable = Thisworkbook.worksheets("yoursheet").UsedRange.Rows.Count
And then insert your new header row and place that value in the cell like:
Thisworkbook.worksheets("yoursheet").Range("a1").Value = newvariable

Related

Excel VBA - Select All Columns & Rows After Last Occupied Column & Row

I'm trying to figure out the code that identifies the last occupied column in the sheet then deletes all columns after that. I'm also trying to figure out the code that identifies the last occupied row in the sheet then delete all rows after that.
So far I've got the idea that I will need to use Rows.Count function but I'm having trouble getting it to select the entire rows after the last occupied row. Same for columns... This is what I've come up with so far which only identifies the last occupied row. Does anyone know how to get it to now select the entire rows after this? And similarly for the entire columns? I can't seem to figure out the code to select the last occupied column like I can with rows... Thank you in advance
Rows:
Sheets("ppCopy").Cells(Rows.Count, 1).End(xlUp).Row
You need to read the code and try to make sense of it and the answer will come to you.
Break down what you already know.
Sheets("ppCopy").Cells(Rows.Count, 1).End(xlUp).Row
Rows.Count = Last Available Row
End(xlUp) = move UP from the last available row (Rows.Count) to the last used row.
How do you get the column then?
Sheets("ppCopy").Cells(1, Columns.Count).End(xlToLeft).Column
Columns.Count = Last Available Column
End(xlToLeft) = Move Left from the last available column (Columns.Count) to the last used Column.
Here is how to delete unused Rows and Columns:
Sub deleteUnused()
Dim lastRow As Long, lastColumn As Integer 'there are a lot of rows compared to columns
Dim lastLetter As String, firstLetter As String
Set wk = ThisWorkbook
With wk.Sheets("Sheet1")
'Get last used rows and columns based on valued from Column A and Row 1
lastRow = .Cells(Excel.Rows.Count, 1).End(Excel.xlUp).Row
lastColumn = .Cells(1, Excel.Columns.Count).End(Excel.xlToLeft).Column
'Delete Rows
.Rows("" & (lastRow + 1) & ":" & Excel.Rows.Count & "").EntireRow.Delete Shift:=xlUp
'Delete columns, tricky because you need the Column Letters instead of the numbers
lastColumn = lastColumn + 1
firstLetter = Split(.Cells(, lastColumn).Address, "$")(1)
lastLetter = Split(.Cells(, Excel.Columns.Count).Address, "$")(1)
.Columns("" & firstLetter & ":" & lastLetter & "").EntireColumn.Delete Shift:=xlLeft
End With
End Sub
J Doe
Here is a code that will search for the value in any cell on any column and then select and delete all rows after that and do the same for the columns. No a very technic or something but will do the work and also give you some ideas. It will also include formulas that display empty cells.
Hope this help.
Sub DeleteRowAndColumns()
With ThisWorkbook.Sheets("ppCopy")
'find any cell no empty in a row in any row
.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Offset(1, 0).EntireRow.Select
'select all the rows
.Range(Selection, Selection.End(xlDown)).Select
Selection.Delete ' clear all the rows
'find the last value in any column
.Cells.Find(What:="*", SearchOrder:=xlColumns, SearchDirection:=xlPrevious, LookIn:=xlValues).Offset(0, 1).EntireColumn.Select
'select columns
.Range(Selection, Selection.End(xlToRight)).Select
Selection.Delete 'clear columns
End With
End Sub

Selecting Range Dynamically till the last cell in VBA

I have a VBA code with the following.
Selection.AutoFill Destination:=Range("H2:J2002")
This can select till the last entry in column J when it has exactly 2002 entries. What I want is a general one which can select between H2 and the last entry in J column. I found the following
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
But I am not understanding, how I can use the value of Lastrow to select the last cell in column J.
Lastrow = ActiveSheet.Cells(Rows.Count, 10).End(xlUp).Row
'lastrow now holds last occupied cell in column 10 ie J
Selection.AutoFill Destination:=Range("H2:J" & lastrow)

Formatting as a table dynamically Excel VBA

I would like to format a certain range in a worksheet as a table in Excel. The formatting will always start in row 10.
In order to do so, I have written the following code:
Set rng = Range(Range("B10"), Range("B10").End(xlUp).SpecialCells(xlLastCell))
Set table = Sheets("Results").ListObjects.Add(xlSrcRange, rng, , xlYes)
table.TableStyle = "TableStyleMedium13"
As of now, the formatting is done from row 10 until the end of the worksheet - even in empty rows. However, I would like the table to be formatted only up until the last row of data and for it to do this dynamically given the fact that the amount of data will vary. How can I do this?
The code below will format all cells from "B10" until last row with data in Column B (it will also format blank rows in the middle, in case you have gaps).
Dim LastRow As Long
With Sheets("Results")
' find last row with data in Column B
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
' set Rng from B10 untill last row with data in Column B
Set Rng = Range("B10:B" & LastRow)
Set Table = .ListObjects.Add(xlSrcRange, Rng, , xlYes)
Table.TableStyle = "TableStyleMedium13"
End With
Range("B" & Rows.Count).End(xlUp)
This should work - will simply identify last populated row.

Excel VBA - Delete Rows Based on Criteria

I have a report that I pull everyday that is placed in a very awekward format. It's contains a variable row count by 4 columns organized into unofficial tables based on the Name of each employee.
What I have is an employee name in column B preceded 2 blank rows above and followed by 1 blank row of data below.
What I want to accomplish is loop through the data, identify cells in column B <> blank, delete the entire 2 rows below that cell, and delete the entire 1 row above that cell.
Below is what I have so far. not much:
Sub test()
Dim currentSht As Worksheet
Dim startCell As Range
Dim lastRow As Long
Dim lastCol As Long
Dim i as integer
Set currentSht = ActiveWorkbook.Sheets(1)
Set startCell = currentSht.Range("A1")
lastRow = startCell.SpecialCells(xlCellTypeLastCell).Row
lastCol = startCell.SpecialCells(xlCellTypeLastCell).Column
For i = lastRow To 1
If Cells(i, "B").Value <> "" Then
End Sub
without making major changes to your code, try this:
For i = lastRow To 1 Step - 1
If Cells(i, "B").Value <> "" Then
Range(Cells(i, "B").Offset(1), Cells(i, "B").Offset(2)).EntireRow.Delete 'delete two below
Cells(i, "B").Offset(-1).EntireRow.Delete ' delete one above
You already get to your non-blank cell (ie Cells(i,"b")). To reference a range in relation to a cell you already have, use OFFSET.
So, and in this order, you select a range of cells from one below your cell Offset(1) to two cells below Offset(2)'. Change this range toENTIREROW` for those cells, and delete.
Then you select the cell above Offset(-1), select the ENTIREROW and delete.
as per your question narrative you'd possibly need to delete all rows that has a blank cell in column "B"
should that be the issue than you could (disclaimer: test it on a copy sheet!) simply go like follows:
Sub test()
With ActiveWorkbook.Sheets(1)
.Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).Offset(, 1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End With
End Sub

Selecting range without knowing number of rows or columns having data in Excel/VBA

I am looking for code for two different types of selection. One code would select in an L shape all of the rows in one column and all of the columns in one row. In the example of having data in the range A1:A10, and data in row 10 only from col A - K. The selection would look like an L. How can you do this without knowing how many rows or columns have data in them?
The second code would have the same data, but need to select the whole range A1:K10 in that example, but the code would need to select whatever range had the data.
i found the answer. i have to do a union. here is the code with the union at the end.
Sub mywork()
Dim ws As Worksheet
Dim lRow As Long, lCol As Long
Dim rng As Range
'~~> Set this to the relevant worksheet
Set ws = [Sheet1]
With ws
'~~> Get the last row and last column
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(lRow, .Columns.Count).End(xlToLeft).Column
'~~> Set the range
Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))
End With
Set rng = Application.Union(Range("A1:A" & lRow), rng)
rng.Select
End Sub
activesheet.usedrange.address should tell you the used range.
In your case something like this should work: [sheet1].usedrange.select (Replaces all the code in the module)
The benefit here is the fact that you are not hard coding "A1:A" against the last identified cell, works well if you have blank rows at the top.