[英]Copy Paste VBA loop
運行我編寫的VBA宏以轉置數據集時出現問題。 主要目標是逐行獲取此數據集,並將其轉置,以便列B:K為新行。
這是我想要做的一個示例:
http://i.imgur.com/4ywn17m.png
我寫過以下VBA,但它所做的一切基本上是在新表中創建一個“影子行”,這不是我想要的。
Sub LoopPaste()
Dim i As Long
Dim firstRow As Long
Dim lastRow As Long
Dim wb As Workbook
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Set wb = ThisWorkbook
Set sheet1 = wb.Sheets("Sheet1")
Set sheet2 = wb.Sheets("Sheet2")
'Find the last row with data
lastRow = sheet1.Range("A:A").Find("*", searchdirection:=xlPrevious).Row
'This is the beginning of the loop
For i = firstRow To lastRow
'Copying Company
sheet2.Range("A" & i) = sheet1.Range("A" & i).Value
'Copying Employees
sheet2.Range("B" & i) = sheet1.Range("B" & i).Value
sheet2.Range("B" & 1 + i) = sheet1.Range("C" & i).Value
sheet2.Range("B" & 2 + i) = sheet1.Range("D" & i).Value
sheet2.Range("B" & 3 + i) = sheet1.Range("E" & i).Value
Next i
End Sub
如何讓循環為每個員工創建一個新行?
我感到無聊,並為你想出了這個。 *應該*非常快速和無痛,但可能需要事先了解范圍。
Private Sub this()
Dim a() As Variant
a = Application.Transpose(Worksheets(1).Range("a1:p1").Value)
ThisWorkbook.Sheets("Sheet1").Range("a1:p1").Value = vbNullString
ThisWorkbook.Sheets("Sheet1").Range("a1:a55").Value2 = a
End Sub
這應該給你的想法:
Sub test()
Dim src As Range, c As Range, target As Range
Dim curRow As Long
Set src = Intersect(Sheet1.Range("A1").CurrentRegion, Sheet1.Range("A1").CurrentRegion.Offset(1, 0))
Set target = Sheet2.Range("a1")
curRow = src.Cells(1, 1).Row
For Each c In src.Cells
If c <> "" Then
target = c.Value
If c.Column = 1 Then
Set target = target.Offset(0, 1) 'next column
Else
Set target = target.Offset(1, 0) 'next row
End If
Else
'back to col 1
If target.Column <> 1 Then Set target = target.Offset(0, -target.Column + 1)
End If
Next c
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.