Selecting a Named Range Only to Last Row - excel

I'm pulling raw data into a template, but I have no guarantee that between teams they'll be using the same UI template to pull the data. I can check to make sure the data I want is there, but they might be in different columns between teams.
So, my macro names the ranges (each is a full column based on the header name) and then will, hopefully, go to select desired named ranges to copy and paste.
Of course, these data sets are various sizes and I feel like I'm tripping over a super simple thing.
What I want to do is select my named range, but only to the last row, and then paste the values into my template. Except, I can't figure out how to only select to the last row.
Here's my current bit of troublesome code:
Dim LastRow as Long
LastRow = ActiveSheet.Cells(Rows.Count, "U").End(xlUp).Row
Range("PullPlacementname" & LastRow).Copy
Running this gives me a run-time error '1004', method 'range' of object failed. This confuses me, cuz I've used this method before successfully.
A slight tinker, below, gave me the same issue
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
I've tried adding an additional Dim
Dim PullPlacementname As Range
Set PullPlacementname = ActiveWorkbook.SheetName("Pull").Range("PullPlacementname")
But the second line gives me a run-time error of '438', object doesn't support this property or method.
Thoughts/suggestions?

You could use something like:
Dim c As Long
With Worksheets("Pull")
c = .Range("PullPlacementname").Column ' assuming the range name only contains one column
.Range(.Cells(1, c), .Cells(.Rows.Count, c).End(xlUp)).Copy
End With

Related

Search for Values in PivotTable and Copy into Different Sheet

I am creating a tool to track project labor costs across multiple sites at our company. I ran into an issue implementing this as not all projects are worked on each month. As such I have had to modify to the tool to account for all projects each month regardless of if they were worked on.
I need to search for 17 individual strings in a PivotTable and if the string is found copy all cells below that string into another tab which calculates the cost. This find and copy function is where I am stuck.
I created some code that copied the data that was specific to a location of the string, but it did not account for the fact the project title (string) will be in the same place in this table each month when this is run. The position of where this data will be copied however does not change.
Appreciate any guidance to get me started...
I am basing this off of the code that you posted in your comment. I found the desired range using:
First Row of the data below the header (assumed to be row 4)
Last Row of data (calculated by finding the largest row that has a cell with data)
Column of the project title match
Sub TRM0000()
Dim Ws As Worksheet
Dim firstRow As Long
Dim lastRow As Long
Dim column As Long
Dim Calc As Range
Set Ws = Sheets("PivotTable")
firstRow = 4
lastRow = Ws.Cells.Find(What:="*", SearchDirection:=xlPrevious).Row
column = Ws.Range("C3:Z3").Find(What:="TRM-0000", LookIn:=xlValues, LookAt:=xlWhole).column
Set Calc = Ws.Range(Ws.Cells(firstRow, column), Ws.Cells(lastRow, column))
Calc.Copy
Sheets("Cost Calc").Range("B5").PasteSpecial xlValues
End Sub
This should be a solution for this specific project title. However, you said you have 17! Instead of recreating this code for each, I would recommend storing the 17 project titles (could be in a tab of the workbook or enumerated in the VBA code), creating a for loop to run through that list, and making the project title and output range references dynamic in the VBA code.

Selecting dynamic, filtered range in VBA

I am attempting to select a dynamic range of filtered data that spans from col. A: col. J without selecting the header (in row 1). From there I need to copy and paste it into a new sheet where I will manipulate it further, but I cannot come up with an efficient or functional way to do this. Based on some code I found on another forum I was able to select all of the "visable cells" in a single column, but I am running into issues trying to select the whole range. I am still very new to vba so forgive my syntax, but my code posted below was an attempt to itterate through Rows.Count and i which was an integer 1-10. If you have any advice on how to do this better and more efficiently I would really appreciate it.
Sub SelectVisibleInColD()
Dim lRow As Long, i As Integer
Set i = 1
Do While i <= 10
With ActiveSheet
lRow = .Cells(.Rows.Count, i).End(xlUp).Row
If lRow < 3 Then Exit Sub
.Cells(1, 1).Offset(1, 0).Resize(lRow - 1).SpecialCells(xlCellTypeVisible).Select
End With
i = i + 1
Loop
End Sub
You can select a range by using Range property of ActiveSheet. You already have the last row and you know that the header is in the first row, so your range starts from position A2 and goes to the last row of column J
ActiveSheet.Range("A2:J"&lRow).SpecialCells(xlCellTypeVisible)
If you want to copy this range, use Copy function like
yourRangeAsAbove.Copy
This function only moves the selection to memory, to paste it, build your destination range and call PasteSpecial function.
I came across this answer googling my issue for: deleting of filtered selection in vba.
However trying your answer &lRow gives me an runtime error 1004, application-defineed or object-defined error
I got around it with this
ActiveSheet.Range("A2:G" & Range("A" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeVisible).Delete
For those that may also get the same issue.

Find the last row with data and autoFit everything

I'm creating an extract in Excel with data from a datatable in my vb.net application. It extracts everything correctly. Now I'm trying to do a bit of design work to make it all pretty. It seems like I'm having an issue with probably something every easy but for some reason I keep getting the below error.
Public member 'XlDirection' on type 'ApplicationClass' not found.
My goal is to find the last row of data in Column A, and then take all cells starting A4 and do .columns.autofit on all columns starting A4 The reason why I'm doing that is because cells A1 - A3 have some long text values in them and I want them to be as they are.
Code:
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim _excel As New Microsoft.Office.Interop.Excel.Application
wSheet = wBook.ActiveSheet()
Dim lRow As Long
With wSheet
lRow = .Range("A" & .Rows.Count).End(_excel.XlDirection.xlUp).Row
.Range("A4" & lRow).Columns.AutoFit()
End With
The original error was due to the fact that XlDirection is an enumeration in the Microsoft.Office.Interop.Excel namespace - it isn't a member of Excel.Application. The bit _excel.XlDirection.xlUp should be:
Microsoft.Office.Interop.Excel.XlDirection.xlUp
The second issue is that the Range you build here...
lRow = .Range("A" & .Rows.Count).End(_excel.XlDirection.xlUp).Row
.Range("A4" & lRow).Columns.AutoFit()
...just appends a row number to the end of "A4". So if the last row was 42, the range you would auto-fit would be "A442". It needs to be ("A4:A" & lRow).
But that still only auto-fits column A. If that's your intent, stop here. If you need to auto-fit all the columns (as indicated by the phrase "all columns starting A4" - my emphasis), read on.
First, you don't need to find the last row number - you're working with Columns when you're performing your auto-fit, so Rows.Count works as well as anything else. You really need to find the right-most column, but I'd skip all of that and just offset the used range down by 3 rows:
With wSheet
.UsedRange.Offset(3).Columns.AutoFit
End With

Populating a list box with data from worksheet

I currently get the following error when I run the code (shown below)
Type Mismatch
To give a bit of context, the worksheet CourseSelection has row 3 populated from A to F. I would like to put the entries from A2:A6 into a listbox. However, I want to generalize this process and make it dynamic to include additional categories if they are added after column F. Therefore I need an automatic way to do this through code similar to what I have below. However, I am getting error messages and I am unsure why.
I defined TaskList as a Range prior to this code. When I hover over xlToRight when I run the code I see a very large negative value (-4191). I am unsure if this is part of the problem.
With Worksheets(CourseSelection).Range("A3")
Set TaskList = Range(.Offset(0, 1), .End(xlToRight))
End With
frmTaskSelection.lbTasks.RowSource = TaskList
Unless you have CourseSelection defined as a constant returning an existing worksheet name then the code will fail on With Worksheets(CourseSelection).Range("A3"). If you want to work with a sheet name CourseSelection you would use With Worksheets("CourseSelection").Range("A3").
Given you error message though you appear to have gotten past this point and your code appears to be failing on frmTaskSelection.lbTasks.RowSource = TaskList. This is because RowSource expects an address
If you were looking to populate the values from a sheet called CourseSelection from A3 to Ax where x is the last used cell, then this code will work from any active sheet.
Please note thate I was unclear as to how you wanted to use further values from column F in addition to A2:A6. If you can provide further guidance/picture etc then the code below can be adapted to suit
Sub test()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Worksheets("CourseSelection")
Set rng1 = ws.Range(ws.[a3], ws.Cells(Rows.Count, "A").End(xlUp))
frmTaskSelection.lbTasks.RowSource = "'" & ws.Name & "'!" & rng1.Address
frmTaskSelection.Show
End Sub

Trouble Figuring out How to replace Cells in a Range with Specific Text - Excel VBScript

I must be having a brain fog at this point because I am certain this is easy to do, and in fact I have managed to create other functions that are a bit more complicated for this project.
Anyway, what I am trying to do. I have a sheet (inventory-data) and in column 1, it lists a company name, which is a same for all the rows. i.e. each of the 1900 or so rows have companyname in the first cell.
Now, while the data will always be the same at each application, the number of rows will change.
So, I need a function that will first determine what the last row of data is in the range, and then change all of the cells in column one of each record to name_company. The company names will always be the same so I can staticly assign them. Here is what I have that does not work.
I was able to get it to work another way, but it would replace text all the way down to the very last row of the worksheet, way beyond where the data stops.
Thanks!
Sub changeCompany() 'Changes company name as pulled from Agemni into proper ETA format
Dim myCell As Range
Dim RngToChange As Range 'The range of cells that need to be changed
Dim LastRow As Long 'Declare variable to help determine the last row on a variable length worksheet
Dim i As Integer
With Worksheets("inventory-data") 'set the range to change
Set RngToChange = .Columns(1)
End With
LastRow = Worksheets("inventory-data").UsedRange.Rows.Count 'Have Excel determine what the last row is.
For i = LastRow To 1 Step -1
RngToChange.Cells.Value = "name_company"
Next i
End Sub
I've always had more success with [SomeCellOrRange].CurrentRegion.Rows.Count e.g:
Range("A1").CurrentRegion.Rows.Count
UsedRange looks for any use of cells, not limited to a continuous tabular block. It also sometimes needs you to re-save the workbook before it will properly shrink after you have eliminated some rows.

Resources