这是我拥有的VBA代码,用于将列从sheet1复制到sheet2。
如何串联工作表1中的两行并将其粘贴到工作表2中的任何列中?
例如,两列都是数字,
在Sheet1中, A列为123456,B列为1
我希望在Sheet2列C上输出为1234561
请帮助,谢谢!
Sub CopyPastingColumns()
Dim erow As Long
Worksheets("Sheet1").Select
erow = ActiveSheet.Cells(1, 1).CurrentRegion.Rows.Count + 1
Worksheets("Sheet1").Select
Worksheets("Sheet1").Range("D6").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Sheets("Sheet2").Cells(erow, 1)
erow = ActiveSheet.Cells(1, 1).CurrentRegion.Rows.Count + 1
Worksheets("Sheet1").Select
Worksheets("Sheet1").Range("I6").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Sheets("Sheet2").Cells(erow, 2)
End Sub
答案 0 :(得分:0)
希望这会有所帮助:
Dim rg As Range
For Each rg In ThisWorkbook.Worksheets("Sheet2").UsedRange.Rows
rg.Cells(1, 3) = rg.Cells(1, 1) & rg.Cells(1, 2)
Next
答案 1 :(得分:0)
我认为使用“选择”功能可能会遇到麻烦。只需使用范围。下面的代码假定您的两个输入范围/选择的大小相同。
Sub CopyPastingColumns()
Worksheets("Sheet1").Select
Worksheets("Sheet1").Range("A1").Select
Dim rgLHS As Range
Set rgLHS = Range(Selection, Selection.End(xlDown))
Worksheets("Sheet1").Range("B1").Select
Dim rgRHS As Range
Set rgRHS = Range(Selection, Selection.End(xlDown))
Dim result As Variant
ReDim result(1 To rgRHS.Rows.Count)
Dim rowIdx As Integer
For rowIdx = 1 To rgRHS.Rows.Count
result(rowIdx) = rgLHS.Cells(rowIdx, 1) & rgRHS.Cells(rowIdx, 1)
Next rowIdx
Dim rgC As Range
Dim wksht As Worksheet
Set wksht = Application.ActiveWorkbook.Sheets("Sheet2")
Set rgC = wksht.Range("C1")
Set rgC = rgC.Resize(UBound(result), 1)
rgC.Value = Application.Transpose(result)
End Sub
答案 2 :(得分:0)
似乎您可能试图同时连接和复制单个条目。因此,这是将Sheet1的最后一个条目(同一行,两列)追加到Sheet2上的列表的另一种方法:
Sub CopyPastingColumns()
Dim wksht As Worksheet
Set wksht = Application.ActiveWorkbook.Sheets("Sheet1")
wksht.Activate
wksht.Range("A1").Select 'your D6
Dim rgLHS As Range
Set rgLHS = Range(Selection, Selection.End(xlDown))
wksht.Range("B1").Select 'your I6
Dim rgRHS As Range
Set rgRHS = Range(Selection, Selection.End(xlDown))
Dim erow As Long
erow = rgLHS.Rows.Count
Set rgLHS = Sheets("Sheet1").Cells(erow, rgLHS.Column)
Set rgRHS = Sheets("Sheet1").Cells(erow, rgRHS.Column)
Set wksht = Application.ActiveWorkbook.Sheets("Sheet2")
wksht.Activate
wksht.Range("C1").Select
Dim rgC As Range
Set rgC = Range(Selection, Selection.End(xlDown))
Dim resultErow As Long
resultErow = rgC.Rows.Count + 1
Set rgC = wksht.Cells(resultErow, rgC.Column)
rgC.Value = rgLHS.Value & rgRHS.Value
End Sub