I need to manipulate an Excel worksheet in code using MS Access and need to find the last used column in my opened Excel file. I would also need to find the last used row in a column.
Here are functions I am using:
Public Function FindLastColumnInWSheet(ws As Worksheet) As Long
Dim LastCol As Long
Dim rng As Range
Set rng = ws.Cells.Find(What:="*", _
After:=ws.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
If rng Is Nothing Then
LastCol = 1
Else
LastCol = rng.column
End If
FindLastColumnInWSheet = LastCol
End Function
Public Function FindLastRowInColumn(wsheet As Worksheet, columnName As String) As Integer
With wsheet
FindLastRowInColumn = .Range(columnName & .rows.Count).End(xlUp).row
End With
End Function
Related
I've written the following code where i want to find the value "BEST Cards Raised:" in column B and where ever this value is delete this and all subsequent rows with data in column B.
I thought what i've written would work but its currently deleting all rows and I cant figure it out :(
Dim lastRow As Long, found As Range
With ActiveSheet
Set found = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Find("BEST Cards Raised:")
If Not found Is Nothing Then
lastRow = .Cells.Find(What:="*", _
After:=.Cells(1, 1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
If lastRow >= found.Row Then
Debug.Print .Rows(found.Row & ":" & lastRow).EntireRow.Delete
End If
End If
End With
If also deleting the row where found then perhaps try the following:
Option Explicit
Public Sub DeleteRows()
Dim lastRow As Long, found As Range
With ThisWorkbook.Worksheets("Sheet1") '<your sheet
Set found = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Find("BEST Cards Raised:")
If Not found Is Nothing Then
lastRow = .Cells.Find(What:="*", _
After:=.Cells(1, 1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
If lastRow >= found.Row Then
.Rows(found.Row & ":" & lastRow).EntireRow.Delete
End If
End If
End With
End Sub
Post debugging
Dim lastRow As Long, foundRow As Variant
With ThisWorkbook.Worksheets("Sheet8")
lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
foundRow = Application.Match("BEST Cards Raised:", .Range("B1:B" & lastRow), 0)
If IsError(foundRow) Then Exit Sub
If lastRow >= foundRow Then .Rows(foundRow & ":" & lastRow).EntireRow.Delete
End With
Try this (comments in code):
Sub DeleteRows()
Dim ws As Worksheet, lastRow As Long, i As Long, j As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
lastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
'determine where to start deleting rows
For i = 1 To lastRow
If Trim(ws.Cells(i, 2).Value) = "BEST Cards Raised:" Then Exit For
Next
'delete all rows from last to found row, looping backwards
For j = lastRow To i Step -1
ws.Rows(j).Delete
Next
End Sub
I am writing a function which will check if the already existing sheet is new or has data. If it consists data then it should return the last row, else it must return the first row. I am using the following code:
Private Function GetLastRow(sheetName As String) As Integer
Dim lastRow As Integer
lastRow = CurrentWorkbook.Sheets(sheetName).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).End(xlUp).Row
GetLastRow = lastRow
End Function
But on debugging, I get an error that says that there is no object set.
Is there any error in my code?
Like this
Option Explicit
Public Sub TEST()
Debug.Print GetLastRow(ActiveSheet.Name)
End Sub
Private Function GetLastRow(ByVal sheetName As String) As Long
Dim lastRow As Long
With ActiveWorkbook.Sheets(sheetName)
On Error GoTo returnVal
lastRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End With
GetLastRow = lastRow
Exit Function
returnVal:
GetLastRow = 1
End Function
With these functions you can always find the last row and last column, you can feed sheet you are looking for the last row or last column and more importantly you can use which column or row is the criterion for you. If you omit the arguments, it will use the active sheet as the worksheet and it will use the first column to find the last row/cell and fist row to find the last column/cell
Function LastRowInColumn(Optional sh As Worksheet, Optional colNumber As Long = 1) As Long
'Finds the last row in a particular column which has a value in it
If sh Is Nothing Then
Set sh = ActiveSheet
End If
LastRowInColumn = sh.Cells(sh.Rows.Count, colNumber).End(xlUp).row
End Function
Function LastColumnInRow(Optional sh As Worksheet, Optional rowNumber As Long = 1) As Long
'Finds the last column in a particular row which has a value in it
If sh Is Nothing Then
Set sh = ActiveSheet
End If
LastColumnInRow = sh.Cells(rowNumber, sh.Columns.Count).End(xlToLeft).Column
End Function
This is the one I use:
Public Function GetLastRow(ByVal arg_ws As Worksheet) As Long
Dim rTest As Range
Set rTest = arg_ws.Cells.Find("*", arg_ws.Range("A1"), xlFormulas, xlPart, , xlPrevious)
If Not rTest Is Nothing Then GetLastRow = rTest.Row Else GetLastRow = 0
End Function
Call it like this:
Sub tst()
MsgBox GetLastRow(ActiveWorkbook.Sheets("Sheet1"))
End Sub
Reference the parent worksheet completely and use a long, not an integer. The end(xlup) was superfluous.
Private Function GetLastRow(sheetName As String) As Long
Dim lastRow As long
with ActiveWorkbook.workSheets(sheetName)
lastRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
end with
GetLastRow = lastRow
End Function
When I am debugging a excel-vba program I came to know my data range is not completely selected.
Below picture shows my data's model and my problem.
I used this code to select the whole range. But this is not working properly.
Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
With rngTemp
Please help me by giving the code for selecting the whole range as given in the figure above.
In your code you are searching by xlByRows. And hence you are getting the address of the last cell which has data which is G7.
Further to my comment, Is this what you are trying?
Sub Sample()
Dim lastrow As Long, lastcol As Long
Dim rng As Range
With Sheets("Sheet1") '<~~ Change this to the relevant sheet
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
lastcol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
lastrow = 1: lastcol = 1
End If
Set rng = .Range("A1:" & _
Split(.Cells(, lastcol).Address, "$")(1) & _
lastrow)
MsgBox rng.Address
End With
End Sub
PLEASE BE AWARE THAT METHOD BELOW IS NOT RELIABLE IN SOME CASES. I WILL LEAVE THIS ANSWER HERE AS A BAD EXAMPLE. FOR DETAILED INFORMATION PLEASE SEE #SiddharthRout 'S EXPLANATION IN THIS LINK
I would use following code to find used range instead of looking for "*" in the cell value:
Sub SelectRange()
Dim LastRow As Long
Dim LastColumn As Long
Dim aWB As Workbook
Dim aWS As Worksheet
Set aWB = ActiveWorkbook
Set aWS = aWB.ActiveSheet '<-You can change sheet name like aWB.sheets("SheetName")
With aWS.UsedRange
LastRow = .Rows(.Rows.Count).Row
LastColumn = .Columns(.Columns.Count).Column
End With
aWS.Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select '<---Cells(1, 1) is the starting cell of range)
End Sub
What's the most efficient way of selecting a column based on a variety of different possible header names? For example, the following gives me the column with header "school":
Rows("1:1").Select
Selection.Find(What:="School", _
After:=ActiveCell, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False).Activate
ActiveCell.Select
Range(ActiveCell, ActiveCell.Offset(6536, 0)).Select
However, "school" could be "college" in another workbook, or "institution" in another. Should I just place the above code within an if-then-else statement and replace "school" with the other possibilities, or is there a more efficient way? And yes, this assumes that none of the possible header names co-exist within the same workbook.
Find is already very efficient. What's not efficient is all those Select's.
I suggest you wrap your Find Header logic into a Function, and refactor your code to avoid Select.
Private Function GetColumn(Header() As Variant, _
Optional NumRows As Long = 0, _
Optional ws As Worksheet = Nothing, _
Optional wb As Workbook = Nothing) As Range
Dim rng As Range, cl As Range
Dim i As Long
If wb Is Nothing Then
Set wb = ActiveWorkbook
End If
If ws Is Nothing Then
Set ws = wb.ActiveSheet
End If
Set rng = ws.UsedRange.Rows(1)
For i = LBound(Header) To UBound(Header)
Set cl = rng.Find(What:=Header(i), _
After:=rng.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not cl Is Nothing Then
With ws
If NumRows = 0 Then
Set GetColumn = Range(cl, .Cells(.Rows.Count, cl.Column).End(xlUp))
Else
Set GetColumn = Range(cl, .Cells(NumRows, cl.Column))
End If
Exit Function
End With
End If
Next
Set GetColumn = Nothing
End Function
Call it like this
Dim rng As Range
Dim Headers() As Variant
Headers = Array("School", "Institution", "College")
' Active Workbook, Active Sheet
Set rng = GetColumn(Headers, 6536)
' All rows in specified column
' Specified sheet in Active workbook
Set rng = GetColumn(Headers, , Worksheets("SomeSheetName"))
I have a spread sheet and I need to look for the last column that has data in it. Then I need to copy this column and copy it to the next blank column.
Is there a way to do this?
I've managed to do it with rows using:
lastrowSrc = Sheets("Overview").Range("B" & Rows.Count).End(xlUp).Row
However this puts B12 in the range, using columns.count simply puts in the number of the column, not the letter
To get the exact column in a worksheet, use this code.
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim LastCol As Long
Set ws = Sheets("Sheet1")
'~~> This check is required else .FIND will give you error on an empty sheet
If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then
LastCol = 1
Else
LastCol = ws.Cells.Find(What:="*", _
After:=ws.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
End If
Debug.Print LastCol
End Sub
EDIT: This is courtesy #brettdj. You can also use the range object to find the last column
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim LastCol As Long
Dim rng As Range
Set ws = Sheets("Sheet1")
Set rng = ws.Cells.Find(What:="*", _
After:=ws.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
If rng Is Nothing Then
LastCol = 1
Else
LastCol = rng.Column
End If
Debug.Print LastCol
End Sub
To get the last column of a particular row, say row 1 use this
Debug.Print ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
Where ws is your relevant worksheet.
Similarly for Row see this.
I found that some of the answers didn't work for my worksheet that had a few rows at the end that were shorter than the others in the worksheet. The code provided just gives the last column of the last row of the worksheet. Instead, I used a loop around code to find the last column in a row, using the Find example to get the last row in the workbook.
Sub Sample()
Dim ws As Worksheet
Dim CurrRow, RowLastCol, LastRow, LastCol As Long
Set ws = Sheets("Sheet1")
'~~> This check is required else .FIND will give you error on an empty sheet
If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then
LastCol = 1
Else
LastCol = 0
LastRow = ws.Cells.Find(What:="*", _
After:=ws.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
' Loop through all the rows of the sheet saving off the highest column count
For CurrRow = 1 to LastRow
RowLastCol = ws.Cells(CurrRow, Columns.Count).End(xlToLeft).Column
If RowLastCol > LastCol Then
LastCol = RowLastCol
End If
Next CurrRow
End If
Debug.Print LastCol
End Sub