VBA:剪切一系列列并将其粘贴为一列

时间:2017-10-02 09:28:47

标签: excel vba excel-vba

我很新,非常感谢你的帮助。我有14000列的数据,每行约30行。

我需要将每列彼此粘贴在一起,这样我只剩下1列。我提供了一个示例屏幕截图:

Example of Data

我对VBA代码的尝试如下(不起作用):

<html>
  <head>
    <link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
    <script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
    <script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
    <script src="https://www.amcharts.com/lib/3/serial.js"></script>
    <script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
  </head>   
<script>
  // Source would be C:/Users/Username/Documents/Visualisation Tool/data/peptide/1A80_HUMAN_R_QDAYDGK_D.js
  var graphValues = [{
    "balloonText": "Control: [[value]]",
    "fillAlphas": 1,
    "id": "Control",
    "lineAlpha": 1,
    "lineColor": "#008000",
    "title": "Control",
    "type": "column",
    "newStack": true,
    "valueField": "Control",
    "hidden": true},
{
    "balloonText": "Control SD: [[value]]",
    "fillAlphas": 1,
    "id": "Control SD",
    "lineAlpha": 1,
    "lineColor": "#000000",
    "title": "Control SD",
    "type": "column",
    "valueField": "Control SD",
    "hidden": true},
{
    "balloonText": "Sample A: [[value]]",
    "fillAlphas": 1,
    "id": "Sample A",
    "lineAlpha": 1,
    "lineColor": "#008080",
    "title": "Sample A",
    "type": "column",
    "newStack": true,
    "valueField": "Sample A",
    "hidden": true},
{
    "balloonText": "Sample A SD: [[value]]",
    "fillAlphas": 1,
    "id": "Sample A SD",
    "lineAlpha": 1,
    "lineColor": "#000000",
    "title": "Sample A SD",
    "type": "column",
    "valueField": "Sample A SD",
    "hidden": true},
{
    "title": "All",
    "id": "all",
    "legendValueText": "",
    "legendPeriodValueText": "",
    "hidden": true
}];
var dataValues = [{
    "glycan": "Hex5HexNAc4NeuAc1",
    "Control": 100.0,
    "Control SD": 10.0,
    "Sample A": 80.0,
    "Sample A SD": 8.0},
    {
    "glycan": "Hex5HexNAc4NeuAc2",
    "Control": 50.0,
    "Control SD": 10.0,
    "Sample A": 4.0,
    "Sample A SD": 4.0}
    ];
</script>
  <script>
    // Source would be C:/Users/Username/Documents/Visualisation Tool/scripts/displayAmCharts.js
    var hiddenValues = [];
    var dataProviderVals;

    function displayAmCharts(additionalData){
      var graphsVals = graphValues;
      dataProviderVals = dataValues;
      var chart = AmCharts.makeChart("chartdiv", {
        "type": "serial",
        "dataProvider": dataProviderVals,
        "legend": {
          "useGraphSettings": true,
          "borderAlpha": 1,
          "align": "center",
          "spacing":  125,
          "listeners": [ {
            "event": "hideItem",
            "method": legendHandler
          }, {
            "event": "showItem",
            "method": legendHandler
          }]
        },
        "categoryField": "glycan",
        "categoryAxis": {
          "autoWrap": true
        },
        "rotate": false,
        "graphs": graphsVals,
        "valueAxes": [
          {
            "stackType": "regular",
            "id": "ValueAxis-1",
            "position": "left",
            "axisAlpha": 1
          }
        ],
        "export": {
          "enabled": true
        }
      });   

      /*
      This manual code below works to replace the data.

      var test = [{
        "glycan": "Hex5HexNAc4NeuAc3",
        "Control": 100.0,
        "Control SD": 10.0,
        "Sample A": 80.0,
        "Sample A SD": 8.0},
        {
        "glycan": "Hex5HexNAc4NeuAc4",
        "Control": 50.0,
        "Control SD": 10.0,
        "Sample A": 4.0,
        "Sample A SD": 4.0}
        ];
      chart.dataProvider = test;
      chart.validateData();
      */

      if(additionalData != undefined){
        // Replace the dataProvider with additionalData from hideValue and redraw the chart.
        chart.dataProvider = additionalData;
        chart.validateData();
      }
      function legendHandler(evt) {
        var state = evt.dataItem.hidden;
        if (evt.dataItem.id == "all") {
          for (var i1 in evt.chart.graphs) {
            if (evt.chart.graphs[ i1 ].id != "all") {
              evt.chart[evt.dataItem.hidden ? "hideGraph" : "showGraph" ]( evt.chart.graphs[ i1 ]);
            }
          }
        }
      }
    }
    function hideValue(){
      var selection = document.getElementById("selection");
      var selectedValue = selection.options[selection.selectedIndex].value;
      hiddenValues.push(selectedValue);
      var newDataProvider = [];
      dataValues.forEach(function(item){
        if(hiddenValues.includes(item.glycan) == false){
          newDataProvider.push(item);
        }
      });
      displayAmCharts(newDataProvider);
    }

    function fillSelection(){
      var select = document.getElementById("selection");
      var options = [];
      dataProviderVals.forEach(function(item){
        options.push(item.glycan);
      });
      for(var i = 0; i < options.length; i++) {
        var opt = options[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
      } 
    }
  </script>

    <body onload="displayAmCharts(); fillSelection()">
        <header>
            <h1><b>Visualisation Tool<b></h1>
        </header>
        <h2></h2>
        <div id="chartdiv"><p>Unfortunately there is no data available.</p></div>

        <div>
            <select class="select" id="selection">
                <option disabled selected>Select an option.</option>
            </select>
            <button class="button" type="button" onclick="hideValue()">Hide</button>
            <button class="button" type="button">Show</button>
        </div>
    </body>
    <script type="text/javascript">
        // Commentary in this version as all JS scripts are included in the same page.
        // Open .JS file that contains data at C > Users > User > Documents > Tool folder > Data > Peptide > peptide based on value stored in localStorage, example would be localStorage.getItem("peptideSelection") = "1A80_HUMAN_R_QDAYDGK_D".
        // var peptide = localStorage.getItem("peptideSelection");
        // var JSLink = "C://Users//Z678187//Documents//StackExample//data//peptide//"+peptide+".js";
        // C://Users/Z678187//Documents/StackExample//data//peptide//1A80_HUMAN_R_QDAYDGK_D.js would be the file location.
        // var JSElement = document.createElement('script');
        // JSElement.src = JSLink;
        // JSElement.onload = OnceLoaded;
        // document.getElementsByTagName('head')[0].appendChild(JSElement);
        // function OnceLoaded() {
        //  displayAmCharts();
        //  fillSelection();
        // }
    </script>
</html>    

请帮助。感谢

4 个答案:

答案 0 :(得分:1)

尝试此操作,假设您的数据从第1行开始。

Sub Cut()

Dim c As Long

Application.screenupdating=false

For c = 14 To Cells(1, Columns.Count).End(xlToLeft).Column 'change 1 if data starts in a different row
    Range(Cells(1, c), Cells(Rows.Count, c).End(xlUp)).Copy Range("A" & Rows.Count).End(xlUp)(2)
Next c

Application.screenupdating=true

End Sub

答案 1 :(得分:0)

看起来像这样:

Option Explicit
Sub MoveData()
    Dim i As Long, lRowData As Long, lRowInput As Long
    ' "H" is 8th column, so you might want
    ' to change starting value of i to 9 or something like that
    For i = 14 To 14000
        ' Last row in "H" column (where you paste data)
        lRowInput = Range("H" & ActiveSheet.Rows.Count).End(xlUp).Row
        ' Last row in i column (from where you draw data)
        lRowData = Cells(ActiveSheet.Rows.Count, i).End(xlUp).Row
        ' Copy values from i column to "H" column
        Range("H" & lRowInput + 1, "H" & lRowInput + lRowData - 1) = _
            Range(Cells(2, i), Cells(lRowData, i)).Value
    Next i
End Sub

答案 2 :(得分:0)

特别是对于大量数据,通过将原始数据读入VBA阵列,通常会更好(更快的执行时间);操纵它;然后将其写回工作表,与对工作表的多次读/写相比。

如果我正确理解您的数据设置(包括N2的连续数据范围,没有空格,并且所有列的长度相同),这是一个在您的数据上使用这种稍微不同的技术的示例。 如果我对您的数据设置的理解不正确,则可能需要对代码进行微小更改

此外,这可能不适用于32位Excel,但值得一试。

Option Explicit
Sub ManyIntoOneColumn()
    Dim WS As Worksheet
    Dim rWhatIHave As Range
    Dim rWhatIWant As Range
    Dim V As Variant, W As Variant
    Dim I As Long, J As Long, K As Long

'set worksheet
Set WS = Worksheets("sheet1") 'change worksheet name

'set range to copy.  If not contiguous, might have to do it differently
Set rWhatIHave = WS.Range("N2").CurrentRegion

'set first cell of WhatIWant
Set rWhatIWant = WS.Range("H2")

'read range into variant array
V = rWhatIHave

'dimension results array
ReDim W(1 To UBound(V, 1) * UBound(V, 2), 1 To 1)

'populate W
K = 0
For I = 1 To UBound(V, 2)
    For J = 1 To UBound(V, 1)
        K = K + 1
        W(K, 1) = V(J, I)
    Next J
Next I

'set rWhatIWant
Set rWhatIWant = rWhatIWant.Resize(rowsize:=UBound(W, 1), columnsize:=1)

'clear results range and write the values
With rWhatIWant
    .EntireColumn.Clear
    .Value = W
    .EntireColumn.AutoFit
End With

End Sub

答案 3 :(得分:0)

您可以将值分配为范围

,而不是复制范围
Sub ConvertRangeToColumn()
    Dim ws As Worksheet
    Dim lastColumn As Long, lastRow As Long
    Dim rng As Range

    Application.ScreenUpdating = False
    Set ws = ThisWorkbook.Sheets("Sheet1")  'change Sheet1 to yout data sheet
    With ws
        lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column   'get last column using Row 1
        For i = 5 To lastColumn             'loop though each column starting from 5
            Set rng = .Range(.Cells(2, i), .Cells(.Cells(.Rows.Count, i).End(xlUp).Row, i)) 'set range to copy
            .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row + 1).Resize(rng.Rows.Count).Value = rng.Value
        Next i
    End With
    Application.ScreenUpdating = True
End Sub