2017-03-06 82 views
1

我的项目涉及将文件夹中的文件中的数据复制到一个excel中。文件夹中的文件具有行中的数据,我需要将数据转换为一个Excel(DataBase Excel)。我发现了一些非常接近我需要的代码,我试图修改该代码以为我工作。它看起来像我只需要修改下面的代码的目标,但我无法得到任何调整工作。VBA:将范围数据从一个工作簿转置为另一个

的完整代码可以在这里找到:http://www.rondebruin.nl/win/s3/win008.htm

我缺少的是从行到列转置数据???

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 

回答

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) 
+0

”destrange.Value = WorksheetFunction.Transpose(SourceRange.Value)“这并没有给我一个错误消息,但它将第一个值放在每行中的相同行数。例如:我有20行我想与第一行中的“测试区域”交叉。在新的excel(destrange)中:A2:A21都有“测试区”。 –

+0

@MichaelKapp您的评论是一个问题或陈述? –

+0

一个问题。转置功能不起作用(I)预期。我需要帮助才能正常工作。你也说de Bruin没有使用复制方法。他使用什么方法?不知道什么谷歌.. –

0

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

相关问题