VBA Excel以转置方式逐行粘贴其他工作簿中的数据

carvr3hs  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(104)

我在同一个目录中有来自不同工作簿的数据,我想将其复制到我的工作表中。不幸的是,它出现在每第五行之后。事实上,我想从第5行开始,但我想稍后将它们逐行放置。


的数据
这段代码发生在我身上:
SubCopyDataFromWorkbooks()

Dim wbSource As Workbook
Dim shTarget As Worksheet
Dim shSource As Worksheet
Dim strfile As String
Dim strFilePath As String
Dim strPath As String

Set shTarget = ThisWorkbook.Sheets("CPP Summary")
strPath = GetPath

If Not strPath = vbNullString Then

strfile = Dir$(strPath & "*.xls", vbNormal)

Do While Not strfile = vbNullString

Set wbSource = Workbooks.Open(strPath & strfile)
Set shSource = wbSource.Sheets("Info for CPP")

Call CopyData(shSource, shTarget)

 wbSource.Close False
 strfile = Dir$()
 Loop
 End If

 End Sub

 Sub CopyData(ByRef shSource As Worksheet, shTarget As Worksheet)

 Const VHead As String = "B1:B4"
Const VMBom As String = "B8:B25"

Dim glrow As Long

glrow = shTarget.Cells(Rows.Count, "A").End(xlUp).Offset(5).Row

shSource.Range(VHead).Copy

With shTarget.Range("A" & glrow)
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
.PasteSpecial Transpose:=True
End With

字符串
有没有办法把这些结果一行一行地放好?

rqdpfwrv

rqdpfwrv1#

你可以在两个特殊的粘贴上使用转置,如下所示:
第一个月
.PasteSpecial Paste:=xlPasteFormats, Transpose:=True
你的代码会看起来像这样:

Sub CopyData(ByRef shSource As Worksheet, shTarget As Worksheet)

    Const VHead As String = "B1:B4"
    Const VMBom As String = "B8:B25"
    
    Dim glrow As Long
    
    glrow = shTarget.Cells(Rows.Count, "A").End(xlUp).Offset(1).Row 'no need to offset per 5 now
    If glrow < 5 Then glrow = 5 'definitely starting at row 5 if there are no lines yet
    shSource.Range(VHead).Copy
    
    With shTarget.Range("A" & glrow)
        .PasteSpecial Paste:=xlPasteValues, Transpose:=True
        .PasteSpecial Paste:=xlPasteFormats, Transpose:=True
    End With
End Sub

字符串

相关问题