I'm creating a VBA application with some forms. When the data is inserted into the Table, Column A calculates a value with a formula. After that I need to copy the resulting value (like paste special, values only) into the adjacent Row
I just need to know how to select the last row everytime. I have tried with ActiveCell, Find, Range etc. but none are working
Selection.Copy
ActiveCell.Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues
Try this:
Selection.Copy
ActiveSheet.Cells(Rows.Count, ActiveCell.Column).End(xlUp).PasteSpecial Paste:=xlPasteValues
From a programming point of view, it's much better to define variables rather than using Selection, .select, or ActiveCell, etc... This code will place the cell you are looking for into the variable r, assuming the first header row (A1) is not empty. If you don't want to make any assumptions about the first or last row, see the last answer on this page. In the code below, this would mean replacing Set r = r.End(xlDown) with Set r = sh.Range("A:A").Find("*", Range("A1"), SearchDirection:=xlPrevious)
Option Explicit
Sub test()
Dim sh As Worksheet, r As Range
Set sh = ThisWorkbook.Worksheets("Sheet1")
Set r = sh.Range("A1")
Set r = r.End(xlDown)
r.Select 'remove after code has been tested and you know it works
End Sub
If you have more questions, just ask. There's a lot of help available to help you program in the proper way here on StackOverflow.
Thanks all,
I fixed it with help of both
LastValue = Range("Table1[Opportunity no.]").End(xlDown).Value
Set ws = Worksheets("Datos")
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row
With ws
.Cells(iRow, 2).Value = LastValue
End With
Related
I am writing VBA code to paste data below already existing data, which i have earlier done as well. this time code is pasting data only when it has value in more than 1 row. If it has value in single row it will copy, but wont paste. Code is below, any help is really appreciated:
range(range("a1:c5"), range("a:c").End(xldown)).select
selection.copy
sheets("finalNo").Cells(Rows.count, 1).End(xLUp).offset(1,0).Pastespecial xlpastevalues
this code will not paste anything if the value is in single row only, but will paste perfectly if its in more than two rows. Unable to solve this. Please help.
Give it a try here:
Sub TestMe()
Dim i As Long
With Worksheets("Sheet1")
i = LastRow(.Cells.Parent)
.Range(.Cells(1, 1), .Cells(i, "C")).Copy
Sheets("finalNo").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
End With
Application.CutCopyMode = False
End Sub
Public Function LastRow(ws As Worksheet, Optional columnToCheck As Long = 1) As Long
LastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
End Function
The "magic" comes from using the function LastRow(), which gives the last used row in the worksheet, named "Sheet1".
The .Cells.Parent refers to the worksheet om the With-clause. But instead it could be written like this i = LastRow(Worksheets("Sheet1")), which is the same.
Suppose this is my initial excel sheet
I want to replace all the non-empty cells in column C with the string "Title" excluding the column header.
The output should be like this:
Thank you!
Try below sub.
Sub FillTitle()
Dim lrow As Long
Dim rng As Range
lrow = Cells(Rows.Count, "C").End(xlUp).Row 'Detect last data entry row in Column C.
For Each rng In Range("C2:C" & lrow)
If rng <> "" Then
rng = "Title"
End If
Next rng
End Sub
Range has Replace method:
Sub ReplaceAll()
With ActiveSheet
Application.Intersect(.UsedRange, .UsedRange.Offset(1), .Columns("C")).Replace What:="*", Replacement:="Tester"
' reset Find/Replace pattern to default for further use
.Cells.Find What:="", LookIn:=xlFormulas, SearchOrder:=xlRows, LookAt:=xlPart, MatchCase:=False
End With
End Sub
For small table, just run a for loop:
for row=2 to something_large
if cells(row,col)<>"" then cells(row,col)="title"
next row
for large table, your best bet is to record a macro: create a filter on the column, filter to nonblank, select all rows, then paste to them. Once you have the macro, modify for general use.
You can choose not use loop as well by using a simple code line like below which will perform the same action.
Range("C2:C" & Range("B" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants).Value = "Title"
I'm trying to create a simple macro for a sheet I use every day at work.
Basically it's about:
Sheet 1 Cell A2:A11 has values in it those values need to be copy pasted into sheet 2 to with an offset each day to the next free column.
What I've got so far is the copy paste with one offset...but I don't know how to say that the offset should happen for the next free column.
Dim rng As Range
Dim ws As Worksheet
Range("A2:A11").Select
Selection.Copy
Sheets("Sheet2").Select
If rng Is Nothing Then
'if nothing found - search for last non empty column
Set rng = ws.Range("2:2").Find(What:="*", LookAt:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
If rng Is Nothing Then
Set rng = rng.Offset(, 1)
ActiveSheet.Paste
End If
If I understand correctly, try just using this instead of all your current code
Range("A2:A11").Copy Sheets("Sheet2").Cells(2, Columns.Count).End(xlToLeft).Offset(, 1)
Set rng = rng.End(xlToRight).Offset(0, 1)
You go all the way right and then one more for the next free column.
Okay, I'm learning scripting for Excel and I've come across something that I just don't know how to do.
I've been asked to help automate the import of a sheet into a sheet and then add some columns off to the side and do some calculations and autofill them to the last row of the imported info. That is no problem. I recently found out however that the sheet that I would import for my office has X number of columns and other offices have Y and Z number of columns in the sheets that they would import. So I'm trying to do this to where it builds the calculation columns at the end of the imported columns. With that bit of background here's where I need some assistance:
Script as written for my office and works:
Range("O1").Select
ActiveCell.FormulaR1C1 = "Remainder"
Range("O2").Select
ActiveCell.FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Range("O2").Select
Range("O2").AutoFill Destination:=Range("O2:O" & Cells(Rows.Count, "B").End(xlUp).Row)
So now I need to make this relational not Cell Address Specific So I came up with this.
Range("A1").select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "Threshold"
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "=IF(RC[-13]>(RC[-5]/3),""Over"",""Under"")"
Range(ActiveCell.Address).AutoFill Destination:=Range(*****How to return the Current Cell Address** : **How to Return the Current Column Letter***** & Cells(Rows.Count, "B").End(xlUp).Row)
I've Tried "ActiveCell.Address":"CHAR(COLUMN()+64))" but That doesn't work and I Just don't know how to get it to set that value to Be the equivalent ?2:? my office running this should autofill from O2:O. But would return P2:P in another.
I'm assuming you want the formula to go in the 1st unused column, no matter how many columns there are. (This will allow for future column use, as well.)
Dim LastCol as integer
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column + 1
Cells(1, LastCol).FormulaR1C1 = "Remainder"
Cells(2, LastCol).FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Cells(2, LastCol).AutoFill Destination:=Range(Cells(2, LastCol), _
Cells(Cells(Rows.Count, "B").End(xlUp).Row, LastCol))
How's this:
Sub test()
Dim lastCol As Integer, lastRow As Integer, formulaCol As Integer
Dim ws As Worksheet
Set ws = ActiveSheet
' First, let's find the last column (#) and last row (#)
With ws.UsedRange
lastCol = .Columns.Count
lastRow = .Rows.Count
End With
' Now, create the "header, two columns offset from last column"
formulaCol = lastCol + 2
Cells(1, formulaCol).Value = "Remainder"
'Now, let's create a range, that we will fill with the MOD() formula. You can do this _
through resizing a range, instead of selecting and autofill
With ws
.Range(.Cells(2, formulaCol), .Cells(2, formulaCol)).Resize(lastRow - 1, 1).FormulaR1C1 = _
"=IF(RC[-" & formulaCol - 1 & "]>(RC[-2]/3),""Over"",""Under"")"
End With
End Sub
I am assuming a few things: Your raw sheets come with the data in one block. In other words, you don't have a gap of columns between data you need. This will get the last used column and row, and use those to enter your formula.
Also, I assume that you are checking that the first part of your mod() formula refers to the info in Col. A, and the second part is the right most column's data. I think I'm not understanding something, so any more info. about how the data is laid out would be helpful. But also, this avoids using "Select", which is good VBA practice from what I've gathered.
I know this has probably already been answered but I have searched through the previous questions and cannot find an answer that works for me.
Basically I have an excel spreadsheet which can be updated daily/weekly/monthly depending on the workflow. What I need is a macro that finds the last 'used' column(Headers are in row 5), inserts a blank column directly to the right of that - (we have a totals table at the end that needs to move along) & copies the entire last used columns data into that newly created column.
It's probably quite a simple code but I've only just started using VBA and hope someone can help!! I'm hoping once I've started doing some bits and pieces I can build up my knowledge!
Thanks in advance
Emma
From here: Copy last column with data on specified row to the next blank column and here: Excel VBA- Finding the last column with data
Sub Test()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim rLastCell As Range
Dim LastCol As Integer
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
LastCol = rLastCell.Column
ws.Columns(LastCol).Copy ws.Columns(LastCol + 1)
End Sub
Lazy minimalist solution:
Sub Macro1()
Dim col As Integer
col = Range("A5").End(xlToRight).Column
Columns(col).Copy
Columns(col + 1).Insert Shift:=xlToRight
End Sub
Though this will crash if there's nothing in cell A5.