选择整行但VBA中的第一列

时间:2017-03-21 07:50:39

标签: excel vba excel-vba

我有以下代码,循环的作用是“复制”工作表1上1行的所有数据,并在工作表2上“粘贴”它。我遇到的问题是我需要在工作表2中粘贴行,但是从列B而不是列A开始。

Do While rowCounter < 2200
    If Cells(rowCounter, colCounter).Value <> "AP Statistics Summary" Then
        ThisWorkbook.Sheets("Throughput Per AP").Rows(throughputAP).Offset(1, 0).Value = ThisWorkbook.ActiveSheet.Rows(rowCounter).Value
        throughputAP = throughputAP + 1
    End If
    rowCounter = rowCounter + 1
Loop

问题发生在这一行:

ThisWorkbook.Sheets("worksheet2").Rows(throughputAP).Offset(1, 0).Value = ThisWorkbook.ActiveSheet.Rows(rowCounter).Value

所以代码运行正常,但数据从A列开始复制到工作表2,我需要它从B列开始

请帮忙!

2 个答案:

答案 0 :(得分:2)

您应该能够将源行的大小调整为比整行宽一列,然后将其复制到A列(即将B:XFD复制到A:XFC):

'Using a With simply to shorten the code
With ThisWorkbook.ActiveSheet.Rows(rowCounter)
    ThisWorkbook.Sheets("worksheet2").Rows(throughputAP + 1).Resize(1, .Columns.Count - 1).Value = _
                  .Resize(1, .Columns.Count - 1).Offset(0, 1).Value
End With

或者,如果您尝试将A:XFC复制到B:XFD,则可以执行

'Using a With simply to shorten the code
With ThisWorkbook.ActiveSheet.Rows(rowCounter)
    ThisWorkbook.Sheets("worksheet2").Rows(throughputAP + 1).Resize(1, .Columns.Count - 1).Offset(0, 1).Value = _
                  .Resize(1, .Columns.Count - 1).Value
End With

或者,如果您乐意对列字母进行硬编码,则可以使用

ThisWorkbook.Sheets("worksheet2").Rows(throughputAP + 1).Range("A1:XFC1").Value = _
                  ThisWorkbook.ActiveSheet.Rows(rowCounter).Range("B1:XFD1").Value

或切换&#34; A1:XFC1&#34;和&#34; B1:XFD1&#34;如果你想走相反的方向

(那些代码替换了你遇到问题的那一行。)

答案 1 :(得分:0)

尝试下面的代码,它会复制EntireRow并使用PasteSpecial xlValues仅粘贴值。

Do While rowCounter < 2200
    If Cells(rowCounter, colCounter).Value <> "AP Statistics Summary" Then
        ThisWorkbook.ActiveSheet.Rows(rowCounter).Copy
        ThisWorkbook.Sheets("Throughput Per AP").Rows(throughputAP).Offset(1, 0).PasteSpecial xlValues
        throughputAP = throughputAP + 1
    End If
    rowCounter = rowCounter + 1
Loop

但是,在您的情况下,我会将Do While替换为For rowCounter

此外,请使用完全限定的Worksheets,而不是ActiveSheet

您的代码的第2版

For rowCounter = 2 To 2200 ' <-- start from 2 (or your start row)
    With Worksheets("YourSheetName") ' <-- put here you sheet's name instead of ActiveSheet
        If .Cells(rowCounter, colCounter).Value <> "AP Statistics Summary" Then
            .Rows(rowCounter).Copy
            ThisWorkbook.Sheets("Throughput Per AP").Rows(throughputAP).Offset(1, 0).PasteSpecial xlValues
            throughputAP = throughputAP + 1
        End If
    End With
Next rowCounter