i want a macro to paste values from clipboard ( values that i have copied from another source)
in transpose to last non empty cell in row E in worksheet "sheet1"
any help?
Try something like this:
Sub WriteFromClipboard()
Dim refRow As Integer
Dim Data As DataObject
Dim DataText As String
On Error Resume Next
'Get row to write data:
refRow = 1 + ThisWorkbook.Sheets("Sheet1").Columns(5).Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
If Err.Number > 0 Then
refRow = 1
End If
Err.Clear
'Get data from clipboard:
Set Data = New DataObject
Data.GetFromClipboard
DataText = Data.GetText
'Write data from clipboard on the spreadsheet:
If Err.Number > 0 Then
MsgBox "Clipboard doesn't contain valid data."
Else
ThisWorkbook.Sheets("Sheet1").Cells(refRow, 5).Select
ThisWorkbook.Sheets("Sheet1").Paste
End If
End Sub
function findLastRowInCol(wks as excel.worksheet, col as long)
dim rng as range
with wks
set rng = .cells(.rows.count, col).end(xlup)
findLastRowInCol = rng.row
end with
end function
To test from the Immediate pane:
debug.print findLastRowInCol(thisworkbook.sheets("sheet1"), 5)
This will give you the row of the last non-empty cell in the specified column. Note that this may not be the last used row of the worksheet; selecting a different column may give you a different result depending which is that column's last non-empty cell.
Edit: replaced activesheet with "sheet1"
Edit: sample code to use in another macro to paste in from some other source,
thisworkbook.sheets("sheet1").cells(findLastRowInCol(thisworkbook.sheets("sheet1"), 5), 5).pastespecial paste:=xlAll
If pasting from another Excel sheet or to strip formatting, you can use e.g. "xlPasteSpecialValues"
Edited to add: to paste a row from another worksheet and transpose, use the above as far as ".pastespecial" then use some variation on:
.pastespecial paste:=xlpastevalues, transpose:=True
The simplest implementation is,
sub PasteToE()
thisworkbook.sheets("sheet1").cells(findLastRowInCol(thisworkbook.sheets("sheet1"), 5),5).pastespecial paste:=xlpastevalues, transpose:=True
end sub
Add a commandbutton to the other worksheet and assign this macro to it. Select your range and copy it, then click the button.
Related
I would like the user to be able to click the green button on the right of each named range to insert a new data entry row below the named range header. The code I have hard codes the insert row number for the first named range. I need a way to have the code to be smart enough to know that the first row below the header of the second, third, & forth named range will changed.
Another big part is that the inserted row needs to have the same formatting (dropdowns, formulas, color, etc.) as the rows below.
First named range button code:
Sub BidSheetAddRow_Materials()
' BidSheetAddRow_Materials Macro
Rows("19:19").Select
Selection.Copy
Rows("19:19").Select
Selection.Insert Shift:=xlDown
Range("A19").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("C19").Select
Selection.ClearContents
Range("K19").Select
Selection.ClearContents
End Sub
Based on the screenshot all table headers are in colA, the first input row is 3 cells below the header, and the first input cell on each table row is a merged cell.
So this works for me:
Sub AddMaterial()
AddRow "MATERIALS"
End Sub
Sub AddRate()
AddRow "RATE"
End Sub
Sub AddRow(TableHeader As String)
Dim f As Range, ws As Worksheet, c As Range
Set ws = ThisWorkbook.Worksheets("Input") 'or whatever
Set f = ws.Columns("A").Find(what:=TableHeader, lookat:=xlWhole) 'find the header
If Not f Is Nothing Then
Set c = f.Offset(3) 'step down to first input row below header
Do While c.Offset(1).MergeArea.Cells.Count > 1 'keep looping while `c` is merged
Set c = c.Offset(1)
Loop
c.Offset(1).EntireRow.Insert shift:=xlDown 'insert
c.EntireRow.Copy c.Offset(1) 'copy
c.Offset(1).EntireRow.ClearContents 'clear new row
Else
MsgBox "Table header '" & TableHeader & "' not found!"
End If
End Sub
Before/after:
My intent is to copy a range together with the objects(radio button) and paste it at an dynamic location (at an offset of 15 columns) then update all the cell references of the newly pasted objects relative to their position. i.e. if location of radio button (object) = "AF22" then linked cell = 1st column of new range + 11 columns to the right (e.g. Column T + 11 columns = Column "AD") hence new cell reference = "AD22"
EDIT: I've removed a part of my code which seemed redundant. The below code perfectly copies and pastes the data and objects. However I need help in the Linkedcell part
`Sub Macro2()
Dim rng, rng1, rng2 As Range, s As Shape, ws As Worksheet, sr As
ShapeRange, Loc As String
Set ws = ActiveWorkbook.ActiveSheet
Set rng = ActiveSheet.Range("E19")
Set rng1 = ActiveSheet.Range("T19:AF34")
Set rng2 = ActiveSheet.Range("E19:Q34")
'Copy the range with text and paste it to the desired location
ActiveSheet.Range("E19:Q34").copy
With rng
rng.Offset(0, 15).Select
ws.Paste
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
'Trying to find option buttons and give them a new cell reference.(linked cell)
With ActiveSheet
'Selection = Range("V19:AC34")
For Each s In .Shapes
'if s.TopLeftCell.Column =
' .Range ("V19:AC34")
If s.Name Like "OptionButton*" Then
s.DrawingObject.LinkedCell = "=" & Chr(s.TopLeftCell.Column) & CStr(s.TopLeftCell.Row)
Debug.Print s.DrawingObject.LinkedCell
'Loc = "AD" & s.TopLeftCell.Row
'Debug.Print Loc
'.Value = xlOff
'Selection.LinkedCell = Range(Loc).Address
'.Display3DShading = False
End If
'End With
Next s
End With
End Sub`
Try the next code to select/copy a shape of a range selection:
Dim ws As Worksheet, s As Shape, rng As Range, optB As OLEObject
Set ws = ActiveSheet
Set rng = sh.Range("your range containing the Option Button to be copied")
With ws
For Each s In .Shapes
If Not Intersect(Range(s.TopLeftCell.Address), Range(rng.Address)) Is Nothing Then
If s.Name = "OptionButton1" Then 'use here your option button name
s.Copy
Exit For
End If
End If
Next s
End With
rng.Cells(1, 1).Offset(0, 15).Select
ws.Paste
'Generic way of identifying the newly pasted Option button and allocate a `LinkedCell` to it:
'Set optB = ws.Shapes(ws.Shapes.Count).OLEFormat.Object
'optB.LinkedCell = "=" & rng.Cells(1, 1).Offset(0, 15).Address
Selection.LinkedCell = rng.Cells(1, 1).Offset(0, 15).Address
A trick must be used in order to do that, but using the ActiveSheet.Shapes...
Using of rng.Cells.Offset(0, 15).Select is not wise. This will select so many cells as the range has. I have chosen to paste it referring the first cell of the range. If you want/need a different position, it will be easy to adapt the code (rng.Cells()), I think.
Edited: I adapted the code to select and copy only a shape named "OptionButton1". Please, take care to use here your real shape name!
I also showed a way to allocate a LinkedCell to the newly created Option Button. I must confess that, looking to your code, I did not understand what cell you tried to link. I used a generic one, the same used for moving the shape. Please use here an appropriate address, according to your need.
I am working on a Macro in Excel that will make a copy of the current worksheet and paste the values into a new worksheet. The worksheet name would be the same just with a number after it [ie Sheet, Sheet1(2)]
My code does this correctly except that it copies and pastes everything to Sheet1(2). I only want it to paste the values (not formulas) from Sheet1 to Sheet1(2). I'm a novice at vba at best so any suggestions are greatly appreciated.
Sub SPACER_Button4_Click()
' Compile Button to Generate Quote
'
'variables definitions
ActiveSheetValue = ActiveSheet.Name
'
'This section creates a copy of the active worksheet and names it with the next corresponding number
Sheets(ActiveSheetValue).Copy After:=Sheets(ActiveSheetValue)
'This section should look for X value in each row, column 4. If value equals X, it deletes the row on the copied sheet
Dim i As Integer
i = 26
Do Until i > 300
If ActiveSheet.Cells(i, 11).Value = "X" Then
Rows(i).Delete
Skip = True
End If
'
If Skip = False Then
i = i + 1
End If
'
Skip = False
Loop
'This part hides columns on Right K thru R of new copied sheet
Sheets(ActiveSheet.Name).Range("K:R").EntireColumn.Hidden = True
End Sub
If the data is contiguous, consider creating a new sheet, selecting and copying the range of data, and pasting onto the new sheet using the below code.
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
I use something like this:
Sub KopyKat()
Dim s1 As Worksheet, s2 As Worksheet
Dim r As Range, addy As String
Set s1 = Sheets("Sheet1")
Set s2 = Sheets("Sheet2")
For Each r In s1.UsedRange
If r.Value <> "" Then
If Not r.HasFormula Then
addy = r.Address
r.Copy s2.Range(addy)
End If
End If
Next r
End Sub
I am having problems with getting a loop to run.
I have a Source1 spreadsheet with a list of values in Column A on the CC's tab. Each number is to be copied individually into Cell B1 on the Template tab of the Source2 spreadsheet.
Cell B1 triggers a consolidation of information (mainly indexed info) and displays it in a template - an aggregate picture of lots of background data. I then Copy A1:K71, and paste this into the Output tab of the Source1 spreadsheet.
I want to work down the list in Column A of the CC's tab, and append each output from the Source2 spreadsheet into the Output tab automatically.
I have the copy/paste working, but I am having problems with the loop.
Selection.Copy
Windows("Source2.xlsx").Activate
Range("B1").Select
ActiveSheet.Paste
Range("A1:K71").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Source1.xlsm").Activate
Sheets("Ouput").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
#Andrew, after reading and re-reading your question, I don't think a loop of any kind is necessary. The macro-recorder results you gave above provide information about how you can solve this. I tested this by creating a Source1 Workbook with values placed in column A on a sheet labeled CC's. I also added a sheet labeled Output. Then, I opened a second Workbook with a sheet labeled Template. Here is the sub-procedure I used to produce the result I think you are describing above:
Sub AndrewProject()
' COMMENT: Declare variables used throughout this procedure
Dim InitialVals As Range
Dim OutputVals As Range
Dim FinalResults As Range
Dim FinalOutput As Range
Dim cell As Variant
' COMMENT: Set the range objects so they are easier to manipulate
Set InitialVals = Workbooks("Source1").Worksheets("CC's").Range("A2:A72")
Set OutputVals = Workbooks("Source2").Worksheets("Template").Range("B2:B72")
Set FinalResults = Workbooks("Source2").Worksheets("Template").Range("A2:K72")
Set FinalOutput = Workbooks("Source1").Worksheets("Output").Range("A2:K72")
' COMMENT: This line copies the values in Source1 Workbook and pastes them into Source2 Workbook
InitialVals.Copy
OutputVals.PasteSpecial xlPasteValues
' COMMENT: Additional code goes here to create the desired output. To simplify things, I put a
' function in Source2, column K that concatenates the string "Output" with InitialVals copied
' from Source1. To emulate your Source2 Template, I placed random values between 1 and 1000 in
' Cells A2:A72 and C2:J72.
' COMMENT: Copy the FinalResults from Source2 "Template" tab into the Source1 "Output" tab
FinalResults.Copy
FinalOutput.PasteSpecial xlPasteAll
End Sub
OK #Andrew...this has got to be my last attempt. I believe this answers your question.
Sub AutomateIt()
' Declare your variables
Dim cell As Range
Dim Src1CC As Range
Dim Src2Template As Range
Dim Src2Calcs As Range
Dim Src1Output As Range
Dim NextRow As Long
Dim count As Integer
' Set the ranges so they can be manipulated
Set Src1CC = Workbooks("Source1").Worksheets("CC").Range("A1")
Set Src2Template = Workbooks("Source2").Worksheets("Template").Range("B1")
Set Src2Calcs = Workbooks("Source2").Worksheets("Template").Range("A1:K72")
Set Src1Output = Workbooks("Source1").Worksheets("Output").Range("A1:K72")
Src2Template.ClearContents
count = 0
' Loop through all the cells and calculate stuff
For Each cell In Src1CC.Range(Src1CC, Src1CC.End(xlDown))
'Determine the next empty row (plus a space for readability)
NextRow = Cells(Rows.count, 1).End(xlUp).Row + 2
'Send a copy of the Src1CC cell value to the Src2Template
cell.Copy Src2Template
'Re-calculate A1:K72 based on cell value
Src2Calcs.Calculate
'Copy Src2Calcs results and paste to Source1 Output
Src2Calcs.Copy
Src1Output.PasteSpecial xlPasteValues
count = count + 1
MsgBox "You have pasted " & count & " results."
'Change Src1Output Range so that the next paste is the next blank row
'plus one additional row for readability.
Set Src1Output = Workbooks("Source1").Worksheets("Output").Range(Cells(NextRow, 1), Cells(NextRow, 11))
Next cell
End Sub
I have a list of references of cells to be deleted. The list of references is in sheet "test_url". The list of references point to cells to be deleted that are in another sheet "main_lists".
What I am after is a macro that takes all the references listed in "test_url" sheet, and select their cells in "main_lists" sheet and delete them.
The following macro is what I recorded for two references only in an attempt to demonstrate my problem that necessitated me to copy the reference from "test_url" sheet, then paste it in the NameBox of "main_urls" sheet to select the contents of the designated cell then delete its contents. This process was done manually one cell at a time for a list of 10-20 addresses/references. However, recently this list is over 2000 entries and it is growing:
Sub DeletePermittedCells()
'DeletePermittedCells Macro
Sheets("test_urls").Select
Range("B2").Select
Sheets("test_urls").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R200045C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
Range("B3").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R247138C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
End Sub
Can someone help with this issue please?
Try this one:
Sub DeletePermittedCells()
Dim rng As Range
Dim arr, c
With Sheets("test_urls")
'storing data in array makes your code much faster
arr = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
End With
With Sheets("main_lists")
Set rng = .Range(arr(1, 1))
For Each c In arr
Set rng = Union(rng, .Range(c))
Next
End With
rng.ClearContents
End Sub
storing addresses in array (rather than reading each cell from worksheet directly) makes your code much faster.
Note, code assumed that your addresses stored in range B2:B & lastrow where lastrow - is row of last cell with data in column B
This assumes that the list of cells to be cleared in is column A:
Sub ClearCells()
Dim s1 As Worksheet, s2 As Worksheet
Dim N As Long, I As Long, addy As String
Set s1 = Sheets("test_url")
Set s2 = Sheets("main_lists")
N = s1.Cells(Rows.Count, "A").End(xlUp).Row
For I = 1 To N
addy = s1.Cells(I, 1).Value
s2.Range(addy).ClearContents
Next I
End Sub