Excel将值从不同的行交换到不同的列

时间:2018-03-24 14:31:02

标签: excel-vba vba excel

我正在寻找一个方法/ makro,它允许我使用不同行(1列)的值显示在1行但不同的列中,如: 老:

value 1
value 2
value 3

新:

value 1    value 2    value 3

由于我必须为大量数据做到这一点,所以makro或类似的东西将是一个很大的帮助。

3 个答案:

答案 0 :(得分:3)

试试此代码

class GWDayCount {
    private static $script_output;
    function __construct( $args ) {
        extract( wp_parse_args( $args, array(
            'form_id'          => false,
            'start_field_id'   => false,
            'end_field_id'     => false,
            'count_field_id'   => false,
            'include_end_date' => true,
            ) ) );
        $this->form_id        = $form_id;
        $this->start_field_id = $start_field_id;
        $this->end_field_id   = $end_field_id;
        $this->count_field_id = $count_field_id;
        $this->count_adjust   = $include_end_date ? 1 : 0;
        add_filter( "gform_pre_render_{$form_id}", array( &$this, 'load_form_script') );
        add_action( "gform_pre_submission_{$form_id}", array( &$this, 'override_submitted_value') );
    }
    function load_form_script( $form ) {
        // workaround to make this work for < 1.7
        $this->form = $form;
        add_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
        if( self::$script_output )
            return $form;
        ?>

        <script type="text/javascript">
        (function($){
            window.gwdc = function( options ) {
                this.options = options;
                this.startDateInput = $( '#input_' + this.options.formId + '_' + this.options.startFieldId );
                this.endDateInput = $( '#input_' + this.options.formId + '_' + this.options.endFieldId );
                this.countInput = $( '#input_' + this.options.formId + '_' + this.options.countFieldId );

                startDateInput1 = $( '#input_' + this.options.formId + '_' + this.options.startFieldId );
                endDateInput2 = $( '#input_' + this.options.formId + '_' + this.options.endFieldId );

                this.init = function() {
                    var gwdc = this;
                    // add data for "format" for parsing date
                    gwdc.startDateInput.data( 'format', this.options.startDateFormat );
                    gwdc.endDateInput.data( 'format', this.options.endDateFormat );
                    gwdc.populateDayCount();
                    gwdc.startDateInput.change( function() {
                        gwdc.populateDayCount();
                    } );
                    gwdc.endDateInput.change( function() {
                        gwdc.populateDayCount();
                    } );
                    $( '#ui-datepicker-div' ).hide();
                }
                this.getDayCount = function() {
                    var startDate = this.parseDate( this.startDateInput.val(), this.startDateInput.data('format') )
                    min1 = startDateInput1;


                    var endDate = this.parseDate( this.endDateInput.val(), this.endDateInput.data('format') );


                    var dayCount = 0;
                    if( !this.isValidDate( startDate ) || !this.isValidDate( endDate ) )
                        return 'neki ni kul';
                    if( startDate > endDate ) {
                        return 0;
                    } else {
                        var diff = endDate - startDate;
                        dayCount = diff ;
                        var test = min1;
                        dayCount = Math.round( dayCount ) + this.options.countAdjust;
                        return test;
                    }
                }

                this.parseDate = function( value, format ) {
                    if( !value )
                        return false;
                    format = format.split('_');
                    var dateFormat = format[0];
                    var separators = { slash: ':', dash: '-', dot: '.' };
                    var separator = format.length > 1 ? separators[format[1]] : separators.slash;
                    var dateArr = value.split(separator);
                    switch( dateFormat ) {
                    case 'mdy':
                        return new Date( 0, dateArr[0] - 1, dateArr[1] );
                    case 'dmy':
                        return new Date( 0, dateArr[1] - 1, dateArr[0] );
                    case 'ymd':
                        return new Date( dateArr[0], dateArr[1] - 1, 0 );
                    }
                    return false;
                }
                this.populateDayCount = function() {
                    this.countInput.val( this.getDayCount() ).change();
                }
                this.isValidDate = function( date ) {
                    return !isNaN( Date.parse( date ) );
                }
                this.init();
            }
        })(jQuery);
        </script>

        <?php
        self::$script_output = true;
        return $form;
    }
    function add_init_script( $return ) {
        $start_field_format = false;
        $end_field_format = false;
        foreach( $this->form['fields'] as &$field ) {
            if( $field['id'] == $this->start_field_id )
                $start_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
            if( $field['id'] == $this->end_field_id )
                $end_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
        }
        $script = "new gwdc({
                formId:             {$this->form['id']},
                startFieldId:       {$this->start_field_id},
                startDateFormat:    '$start_field_format',
                endFieldId:         {$this->end_field_id},
                endDateFormat:      '$end_field_format',
                countFieldId:       {$this->count_field_id},
                countAdjust:        {$this->count_adjust}
            });";
        $slug = implode( '_', array( 'gw_display_count', $this->start_field_id, $this->end_field_id, $this->count_field_id ) );
        GFFormDisplay::add_init_script( $this->form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );
        // remove filter so init script is not output on subsequent forms
        remove_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
        return $return;
    }
    function override_submitted_value( $form ) {
        $start_date = false;
        $end_date = false;
        foreach( $form['fields'] as &$field ) {
            if( $field['id'] == $this->start_field_id )
                $start_date = self::parse_field_date( $field );
            if( $field['id'] == $this->end_field_id )
                $end_date = self::parse_field_date( $field );
        }
        if( $start_date > $end_date ) {
            $day_count = 0;
        } else {
            $diff = $end_date - $start_date;
            $day_count = $diff; // secs * mins * hours
            $day_count = round( $day_count ) + $this->count_adjust;
        }
        $_POST["input_{$this->count_field_id}"] = $day_count;
    }
    static function parse_field_date( $field ) {
        $date_value = rgpost("input_{$field['id']}");
        $date_format = empty( $field['dateFormat'] ) ? 'mdy' : esc_attr( $field['dateFormat'] );
        $date_info = GFCommon::parse_date( $date_value, $date_format );
        if( empty( $date_info ) )
            return false;
        return strtotime( "{$date_info['year']}-{$date_info['month']}-{$date_info['day']}" );
    }
}

基于T.M的解决方案,这里有一个简短的版本

Sub Test()
Dim ws          As Worksheet
Dim arr         As Variant

Set ws = ThisWorkbook.Worksheets("Sheet1")
arr = Application.Transpose(ws.Range("A1:A" & ws.Cells(Rows.Count, 1).End(xlUp).Row).Value)

ws.Range("B1").Resize(, UBound(arr)).Value = arr
End Sub

答案 1 :(得分:3)

您可以将PasteSpecialTranspose:= True一起使用。

<强> 代码

Option Explicit

Sub TransposeRow()

Dim Sht          As Worksheet

Set Sht = ThisWorkbook.Worksheets("Sheet1") ' modify "Sheet1" to your sheet's name
With Sht
    .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row).Copy

    .Range("B1").PasteSpecial Paste:=xlPasteAll, Transpose:=True
End With

End Sub

答案 2 :(得分:1)

正如@YasserKhalil的有效回答的附录以及对上述评论中的其他问题的回复:

  

&#34;是否可以将最大行设置为X(如只读取29行并将其写入1行)和标记单元格的位置(我标记A201,它使用A201到A229和把它写在B201,C201等等)?&#34;

►您可以轻松地将最大行定义为常量,并按如下方式使用它:

Sub Test2()
' Do nothing if you aren't in wanted sheet
  If Not ActiveCell.Parent.Name = "Sheet1" Then Exit Sub

  Const NROWS     As Long = 29
  Dim arr         As Variant
  Dim nStart      As Long
  Dim sRng        As String
' Define data range as string
  nStart = ActiveCell.Row
  sRng = ActiveCell.Address & ":" & Replace(ActiveCell.Address, nStart, nStart + NROWS - 1)
' get transposed data
  arr = Application.Transpose(Range(sRng).Value)
' write transposed data to new defined range
  ActiveCell.Offset(0, 1).Resize(, NROWS).Value = arr
End Sub