VBA is not selecting the last row in my data [duplicate] - vba

This question already has answers here:
Find last used cell in Excel VBA
(14 answers)
Closed 6 years ago.
I feel like I am missing something.
I have a table with ID, Name, Status as headers.
The table's headers start at B2 and data starts at B3
The table is dynamic and generated by vba code from another workbook.
There may be times it is filtered data but there are no gaps in the table.
There are times a user will select someone in the Name column (C).
A button click should bring them down to the last record.
I get that there are lots of ways to accomplish this but I cannot seem to get any of them to work and I can't figure out why.
Here is my current code but I have tried UsedRange, CurrentRegion, Table names, the whole works.
Sub MoveToLastRow()
Dim LastRow As Long
LastRow = ActiveSheet.Cells(Rows.Count, "C").End(x1Up).Row
End Sub
I click on the button or try to step through the code with a name selected and it just does nothing.
Thank you for your input.
~Don

Add:
Application.GoTo Range("C" & LastRow)
at the end of your code to make the cursor move to that cell.

You may use the following simple VBA code snippet to select the last cell with data in Column "C":
Sub MoveToLastRow()
ActiveSheet.Range("C" & Rows.Count).End(xlUp).Select
End Sub
Note: your original code contains a syntax error, thus it doesn't work: End(x1Up).Row should be written as End(xlUp).Row. Following is the corrected code snippet performing the same action (i.e. selecting the last cell with data in Column "C")
Sub MoveToLastRow()
Dim LastRow As Long
LastRow = ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Row
ActiveSheet.Range("C" & LastRow).Select
End Sub
Hope this may help.

In your code change .End(x1Up) to .End(xlUp) if you use Option Explicit at the top of your code it will show you that VBA thought it was a variable.

Related

How to select last cell in a column and insert it into another sheet in last open cell

Just started coding with excel in VB. The problem I am having is this:
I want to copy the last cell in a column on one sheet, then paste it into the next open cell in a column on the next sheet. If it is at all possible can I have it do this automatically instead of having to call the function or click a button every time?
Here is what I have so far:
Sub UpdatePromoCalendar()
Dim LR As Long
Dim TR As Long
LR = WorksheetFunction.Max(20, Range("A" & Rows.Count).End(xlUp).Row + 1)
TR = WorksheetFunction.Max(20, Range("O" & Rows.Count).End(x1Up).Row - 1)
Sheets("Sheet1").Range("O" & TR).CopySpecial xlCopyValues
Sheets("Sheet2").Range("A" & LR).PasteSpecial xlPasteValues
End Sub
Now it works using the paste option above with the LR. But I can't get it to copy the last populated cell in the column.
Sorry if it's a simple fix I am new to using excel macros and VB in excel.
Thanks for the help in advance!
Instead of using a macro I decided to redo my spreadsheet and go with a pivot table with slicers. I created separate sheets with each item and added a new column called price master. This way I could then filter the results with the slicers showing a cleaner and easier to use template.
The macro was a lot of trouble and basically was taking the place of the slicer which was a waste of time doing in the long run.

Copying Cells from Workbook to Workbook Results in "Subscript Out of Range"

Good day.
I am trying to write a code that will essentially select cells (left to right) from "A - M" and (downwards) up until the last used row.
Then, once selected, I was to copy them to another workbook.
This is the code that I tried to use:
ActiveWorkbook.Worksheets("Sheet1").Range("A1:M" & LastRow).Copy _
Workbooks("Converter.xlsm").Worksheets("Sheet1").Range("A1").CurrentRegion
Everything else in the code works except for this line.
And the result is this:
Run-time error '9':
Subscript out of range
Thanks.
PS. The "LastRow" Variable I used, I just pulled that out of a tutorial. That's not a personal user-defined variable, so I am not sure if that's actually from VBA's Documentation.
You mentioned you do not have a calculation for LastRow.
Always put Option Explicit at the top of your module. It forces you to declare your variables and will help you recognize if something you got from another coder is "built-in" or not.
See this post about determining the last row in a range.
From that post, you should have a calculation such as the following before your line of code ...
LastRow = Sheets("Sheet1").Range("A" & Sheets("Sheet1").Rows.Count).End(xlUp).Row
Please close all the workbooks and reopen and then try with below code
Sub test()
Dim lastrow As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
ActiveWorkbook.Worksheets("Sheet1").Range("A1:M" & lastrow).Copy Workbooks("Converter.xlsm").Worksheets("Sheet1").Range("A1")
End Sub

How to move to next blank cell?

I have data on multiple sheets in a workbook that I want copied all to one sheet in that same workbook. When I run the macro, I would like it to start by deleting the current data in the "iPage Data Export" sheet and then replacing it with data from the other sheets.
I want the process to occur one column at a time since I may not bring over everything. Right now I am trying to learn how to do just one column.
I was able to get it to copy all of the contents of a column from one sheet, but when it moves to the next sheet, it overwrites the existing data. In the end, I only get one sheets worth of data copied.
Here are my 4 problems:
How do I make it clear the data on this sheet before running the routine?
How can I make it start each copy function at the bottom of that row (i.e. after the last cell with a value)? I have tried many of the suggestions on this and other boards without success. I will admit I am not very experienced in this.
How can I make it copy to a particular column (currently it just seems to default to A.
How can I concatenate multiple columns during the paste function? I.e. what if I want it to insert: A2&", "B2 instead of just A2
Sub CombineData()
Dim Sht As Worksheet
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name <> "iPage Data Export" Then
Sht.Select
Range("C:C").Copy
Sheets("iPage Data Export").Select
ActiveSheet.Paste
Else
End If
Next Sht
End Sub
How do I make it clear the data on this sheet before running the routine?
Sht.Cells.ClearContents
How can I make it start each copy function at the bottom of that row (i.e. after the last cell with a value)? I have tried many of the suggestions on this and other boards without success. I will admit I am not very experienced in this.
Range("C" & Rows.Count).End(xlUp).Offset(1, 0)
In detail:
Rows.Count will return the number of rows in the sheet, so in the legacy style *.xls workbooks this would return the number 65,536. Therefore "C" & Rows.Count is the same as C65536
Range("C" & Rows.Count).End(xlUp) is the same as going to C65536 and pressing Ctrl + ↑ - The command End(xlDirection) tells the program to go the last cell in that range. In this case, we would end up at the last cell containing data in column C.
.Offset(1, 0) means that we want to return the range offset by an amount of rows and/or columns. VBA uses RC (Rows Columns) references, so whenever you see something like the Offset() function with two numbers being passed as the arguments, it usually relates to the row, and the column, in that order. In this case, we want the cell that is one row below the last cell we referenced.
All-in-all the phrase Range("C" & Rows.Count).End(xlUp).Offset(1, 0) means go to the last cell in column C, go up until we hit the last cell with data, and then return the cell below that - which will be the next empty cell.
How can I make it copy to a particular column (currently it just seems to default to A.
Range("C:C").Copy Destination:=Sheets("iPage Data Export").Range("A:A")
You can pass the Destination argument in the same line and actually bypass the clipboard (faster and cleaner)
How can I concatenate multiple columns during the paste function? I.e. what if I want it to insert: A2&", "B2 instead of just A2
Lets say you wanted to reference column A, B, and F - just use:
Range("A1, B1, F1").EntireColumn
To summarise, you could streamline your existing code to something like (untested):
Sub CombineData()
Dim Sht As Worksheet
For Each Sht In ActiveWorkbook.Worksheets
If Sht.Name <> "iPage Data Export" Then
Sht.Range("C1:C" & Cells(Sht.Rows.Count, 3).End(xlUp).Row).Copy Destination:=Sheets("iPage Data Export").Range("A:A")
End If
Next
End Sub
This should do for the copying:
Sub CombineData()
Dim sheet As Worksheet
For Each sheet In Worksheets
If (sheet.Name <> "iPage Data Export") Then
sheet.Select
Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Worksheets("iPage Data Export").Activate
Cells(1, ActiveCell.SpecialCells(xlCellTypeLastCell).Column + 1).Select
ActiveSheet.Paste
End If
Next
End Sub
For the concatenation you need to be more specific - but I guess you should open a new question with a clearer focus if you need specific help on that.

How do I count the number of non-zeros in excel?

I am trying to make a macro that will go through a whole workbook and count the number of days a employee worked. The sheets have the work broken out in days so all T have to find is the days that are not zero. I have tried to use COUNTIF(A11:A12,">0") and I get the error Expected : list separator or ). I am using a For Each loop to work through the sheets. I would like to put all the information on a new sheet at the end of the workbook with the name of the employee and the days worked. I am very new to visual basic but am quite good with c#.
I now have gotten this far
Option Explicit
Sub WorksheetLoop2()
' Declare Current as a worksheet object variable.
Dim Current As Worksheet
Dim LastColumn As Integer
If WorksheetFunction.CountA(Cells) > 0 Then
' Search for any entry, by searching backwards by Columns.
LastColumn = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
End If
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
Current.Range("A27") = Application.WorksheetFunction.CountIf(Current.Range(Cells(11, LastColumn), Cells(16, LastColumn)), ">0")
Current.Range("A28") = Application.WorksheetFunction.CountIf(Current.Range("Al17:Al22"), ">0")
Next
End Sub
When I run this I get an error saying method range of object'_worksheet' failed. I also haven't been able to find a way to get the information all on the summary sheet.
VBA Solution, in light of your last comment above.
Good VBA programming practice entails always using Option Explicit with your code, that way you know when you don't have variables declared correctly, or, sometimes, if code is bad! In this case you would have picked up that just writing A27 does not mean you are returning the value to cell A27, but rather just setting the value you get to variable A27. Or maybe you wouldn't know that exactly, but you would find out where your problem is real quick!
This code should fix it for you:
Option Explicit
Sub WorksheetLoop2()
'Declare Current as a worksheet object variable.
Dim Current As Worksheet
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
Current.Range("A27") = Application.WorksheetFunction.CountIf(Current.Range("A11:A12"), ">0")
Next
End Sub
In case it helps, Non-VBA solution:
Assuming you have a Summary sheet and each employee on a separate sheet, with days in column A and hours worked in column B, enter formula in formula bar in B1 of Summary and run down the list of names in column A.

VBA VLOOKUP Convert to Values Gives #N/A

I'm having some trouble with VLOOKUP in my VBA. Here's an example of the code I'm using:
Sub Macro15()
'
' Macro15 Macro
Dim LR As Long
LR = Cells(Rows.Count, "A").End(xlUp).Row
Range("B1:B" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-1],'https://internal_sharepoint_address
/[Vendor_Information.xlsx]Sheet1'!R3C3:R150C18,4,FALSE)"
Range("C1:C" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-2],'https://internal_sharepoint_address
/[Vendor_Information.xlsx]Sheet1'!R3C3:R150C18,5,FALSE)"
With Range("B1:C" & LR)
.Value = .Value
End With
End Sub
The problem is that the values in Columns B & C (the VLOOKUP formulas) return a value of #N/A.
However, if I stop the code before converting the formula to values (the "With Range("B1:C" & LR)" line), the VLOOKUP formula returns the correct values.
Also strange - if I clear the contents of Columns B & C and re-run the above code, the values return fine. If I try to add a second cycle to the VBA, however, it does NOT work.
Any wisdom that anyone can provide would be a huge help. I've been stuck on this for a long time, and I'm just at my wit's end.
Thanks all,
David
You'll probably need to add in a step that runs a calculation cycle before you try to replace with the value:
Application.Calculate
Edit from comment: I would imagine that retrieving lookup data from a linked workbook on a Sharepoint site would take awhile. Maybe add some delay loops? Can you make two separate macros (one ending with the formulas, and a second one starting at the Paste Values), and run them separately with a pause in between?