简体   繁体   中英

Excel - Copy selected cell and paste to the end of a column in another worksheet

I'm very new at VBA and looking to copy the selected cell's contents and paste them to the next available row in Column B of Worksheet "Draft".

I was able to figure 2 other simple macros I needed out but could figure out how to put them together to figure this out.

Sub CopyName()
'Copy's selected cell to cell K2 within same worksheet... which then triggers vlookups with additional info

Selection.Copy
Range("K2").Select
ActiveSheet.Paste
End Sub

Sub SelectPlayer()
'Copies name pasted in K2 , to next available row in column B of other worksheet

Worksheets("Draft").Range("B" & Rows.Count).End(xlUp).Offset(1) =       Worksheets("Dashboard").Range("K2").Value




 End Sub

okay, try this:

Sub CopyName()
Worksheets("Draft").Range("B" & Rows.Count).End(xlUp).Offset(1, 0) = Worksheets("Dashboard").Range("K2").Value
End Sub

You would need to actually figure out the next available row in the sheet "Draft". Use this:

Sub CopyName()
'Copy's selected cell to cell K2 within same worksheet... which then triggers vlookups with additional info

Selection.Copy
Range("K2").Select
ActiveSheet.Paste
End Sub

Sub SelectPlayer()
'Copies name pasted in K2 , to next available row in column B of other worksheet
Dim intNextEmptyCell As Integer
'assuming data on sheet "Draft" starts from row 2 column 1
intNextEmptyCell = Get_Count(2, 1, Worksheets("Draft"), true)
Worksheets("Draft").Range("B" & Strings.Trim(Str(intNextEmptyCell+1))).End(xlUp).Offset(1) =  Worksheets("Dashboard").Range("K2").Value
End Sub

Get_Count is a function that I've written that gets the number of data of a column or row. Using that function you can get the number of rows of data in column "B" in the draft sheet and copy whatever is in "K2" to the next available cell. You can get more information about that function in my blog, Get Column and Row Data Count

'intRow: The row your data starts
'intColumn: The column your data starts
'wrkSheet: The worksheet object
'flagCountRows: True if trying to get the number of rows
Public Function Get_Count(ByVal intRow As Integer, ByVal intColumn As Integer, ByRef wrkSheet As Worksheet, _
ByVal flagCountRows As Boolean) As Integer
Dim i As Integer
Dim flag As Boolean

i = 1
flag = True
While flag = True
    If flagCountRows = True Then
        If wrkSheet.Cells(i + intRow - 1, intColumn) <> "" Then

           i = i + 1
        Else
           flag = False
        End If
    Else
        If wrkSheet.Cells(intRow, intColumn + i–1) <> "" Then
           i = i + 1
        Else
           flag = False
        End If
    End If
Wend

Get_Count = i–1
End Function

String.Trim(Str()) Converts the integer data type to a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM