Excel - 复制选定的单元格并粘贴到另一个工作表中的列的末尾

时间:2014-03-05 04:20:56

标签: excel vba

我是VBA的新手,希望复制所选单元格的内容并将其粘贴到工作表“草稿”B列的下一个可用行中。

我能够找出我需要的其他两个简单的宏,但可以弄清楚如何将它们组合在一起来解决这个问题。

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

2 个答案:

答案 0 :(得分:0)

好的,试试这个:

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

答案 1 :(得分:0)

您需要实际找出工作表“草稿”中的下一个可用行。使用此:

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是我编写的一个函数,用于获取列或行的数据数。使用该函数,您可以在草稿表中的“B”列中获取数据行数,并将“K2”中的任何内容复制到下一个可用单元格中。您可以在我的博客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())将整数数据类型转换为字符串。