vba - 该程序选择整行,如何将选择限制为A到M

标签 vba excel

Sub Test()

Dim Cell As Range

With Sheets(1)
    ' loop column H untill last cell with value (not entire column)
    For Each Cell In .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        If Cell.Value = "0" Then
             ' Copy>>Paste in 1-line (no need to use Select)
            .Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
        End If
    Next Cell
End With

End Sub

最佳答案

尝试

Sub Test()

Dim Cell As Range

With Sheets(1)
    ' loop column H untill last cell with value (not entire column)
    For Each Cell In .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        If Cell.Value = "0" Then
             ' Copy>>Paste in 1-line (no need to use Select)
             Dim targetRow As Long
             targetRow = Cell.Row
            .Range("A" & targetRow & ":H" & targetRow).Copy Destination:=Sheets(4).Rows(Cell.Row)
        End If
    Next Cell
End With

End Sub

因为这会产生奇怪的重复粘贴,你真的想要吗?注意我用 currentCell 替换了变量单元格以避免混淆
Option Explicit

Sub Test()

    Dim currentCell As Range

    With Sheets(1)

        For Each currentCell In .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        
            If currentCell.Value = "0" Then
        
                Dim targetRow As Long
                targetRow = currentCell.Row
                .Range("A" & targetRow & ":H" & targetRow).Copy Destination:=Sheets(4).Cells(currentCell.Row, 1)

            End If
        
        Next currentCell
    
    End With

End Sub
和:
正如@DisplayName 所指出的,您在评论中提到了 H 列。如果你打算循环这个然后改变:
For Each currentCell In .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
为了
 For Each currentCell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)

关于vba - 该程序选择整行,如何将选择限制为A到M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49334481/

相关文章:

vba - 使用 Excel 中定义的范围,替换打开的 Word 文档中的 [文本]

excel - VBA检查文件是否存在

excel - VBA 中匹配函数所需的错误对象

c# - 从宏调用 Excel VBA 加载项

VBA:Sub 的 const 参数 - 避免修改按值传递的参数值

vba - 错误 506 : Class not defined: 'FileSystemObject'

excel - 删除所有工作表中除指定列外的所有列

vba - Excel VBA - 工作表类的复制方法失败 - 用于正常运行

excel - 如何使用数组公式对 excel 3d 数组中的列、行、列求和

java - 用于处理 Excel 的库 - jxl?