VBA:将一组范围数据从一个工作簿转换到另一个工作簿

时间:2017-03-06 18:42:35

标签: excel vba excel-vba range transpose

我的项目涉及将文件夹中文件的数据复制到一个excel中。文件夹中的文件包含行数据,我需要将数据转换为一个Excel(DataBase Excel)。我找到了一些非常接近我需要的代码,我正在尝试修改该代码以便为我工作。看起来我只需要修改下面代码中的destrange,但我无法进行任何调整。

可在此处找到完整代码:http://www.rondebruin.nl/win/s3/win008.htm

我将丢失的数据从Rows转移到列???

 If Not sourceRange Is Nothing Then

                SourceCcount = sourceRange.Columns.Count

                If Cnum + SourceCcount >= BaseWks.Columns.Count Then
                    MsgBox "Sorry there are not enough columns in the sheet"
                    BaseWks.Columns.AutoFit
                    mybook.Close savechanges:=False
                    GoTo ExitTheSub
                Else

                    'Copy the file name in the first row
                    With sourceRange
                        BaseWks.Cells(1, Cnum). _
                                Resize(, .Columns.Count).Value = MyFiles(Fnum)
                    End With

                    'Set the destrange
                    Set destrange = BaseWks.Cells(2, Cnum)
                    'Set destrange = BaseWks.Range("A" & 1)

                    'we copy the values from the sourceRange to the destrange
                    With sourceRange
                        Set destrange = destrange. _
                                        Resize(.Rows.Count, .Columns.Count) '.PasteSpecial Paste:=xlValues, Transpose:=True
                        'destrange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
                    End With
                    destrange.Value = sourceRange.Value

                    Cnum = Cnum + SourceCcount
                End If
            End If
            mybook.Close savechanges:=False
        End If

2 个答案:

答案 0 :(得分:0)

请注意,de Bruin没有使用Copy方法。试试这个(未经测试)

'Set the destrange
                Set destrange = BaseWks.Cells(2, Cnum)
                'Set destrange = BaseWks.Range("A" & 1)

                'we copy the values from the sourceRange to the destrange
                With SourceRange

                 'NOTE we reverse the rows and columns
                    Set destrange = destrange. _
                                    Resize(.Columns.count, .Rows.count)
                End With

               'NOTE we transpose the SourceRange.  If SourceRange has a huge number of rows, might have to do this manually.

                destrange.Value = WorksheetFunction.Transpose(SourceRange.Value)

答案 1 :(得分:0)

罗恩 您发布的解决方案是正确的。我在更新代码时遇到了错误。 注意。我还必须进行其他更新,例如创建和交换Cnum for Rnum,以便数据将按行而不是列添加。那是你的时间和快速反应。 我并没有试图坚持de Bruin正在使用复制方法,我试图弄清楚他使用的方法的名称。我想它确实没有名字。他只是使用数组来移动数据。