简体   繁体   English

如何使用VBA循环数据空行?

[英]How to loop through data with empty rows with VBA?

I am trying to loop through non-contiguous data - basically loop through all the cells that have value in Range("K:M") taking into consideration that between the data there might be some empty rows and I will need to skip and move on and merge the 3 cells into 1 in Range("H4") . 我试图循环遍历非连续数据 - 基本上遍历所有具有Range("K:M")值的单元格,考虑到数据之间可能存在一些空行,我需要跳过并移动在Range("H4")中将3个单元格合并为1

Tried different approaches but every time it hits the empty row it stops. 尝试了不同的方法,但每次它击中空行停止。 Below will be more like an infinite loop that does what I need but can't work how to break out at some point when there is no more data. 下面将更像是一个无限循环,它可以满足我的需求,但是当没有更多数据时,无法在某些时候突破。

Sub GenerateStyleFabricColourV2()
        Dim srcData As Range
        Dim RowNum As Long
        RowNum = 4
        Set srcData = Range("K:M")
        If Not IsEmpty(srcData.Value) Then
          Do While IsEmpty(RowNum) = False
            Cells(RowNum, 8).Value = Cells(RowNum, 11).Value & Cells(RowNum, 12).Value &  Cells(RowNum, 13).Value
            RowNum = RowNum + 1
          Loop
        End If
        Range("H4").Select
        Range(Selection, Selection.End(xlDown)).Select
     End Sub

IsEmpty refers to a cell that may or may not have a value (ie blank or not blank). IsEmpty是指可能有或没有值的单元格(即空白或非空白)。 It isn't intended to do anything with an integer. 它不打算用整数做任何事情。

Sub GenerateStyleFabricColourV2()
    Dim srcData As Range
    Dim rowNum As Long, lastRow As Long

    With Worksheets("sheet2")
        lastRow = Application.Max(4, _
                    .Cells(.Rows.Count, "K").End(xlUp).Row, _
                    .Cells(.Rows.Count, "L").End(xlUp).Row, _
                    .Cells(.Rows.Count, "M").End(xlUp).Row)
        With .Cells(4, "H").Resize(lastRow - 4 + 1, 1)
            .FormulaR1C1 = "=rc[3]&rc[4]&rc[5]"
            .Value = .Value2
        End With
    End With
End Sub
Sub GenerateStyleFabricColourV2()
    Dim srcData As Range, rcell As Range

    Set srcData = ThisWorkbook.Sheets("Sheet1").Range("K4:K" & ThisWorkbook.Sheets("Sheet1").Cells(Sheet1.Rows.Count, "K").End(xlUp).Row)
    For Each rcell In srcData.Cells
        rcell.Offset(0, -3).Value = rcell.Value & rcell.Offset(0, 1).Value & rcell.Offset(0, 2).Value
    Next rcell

 End Sub

This is pretty straight forward. 这很简单。 I like looping through the one column and using offset. 我喜欢循环遍历一列并使用偏移量。 I might be over simplifying it though. 我可能会过度简化它。

This simple code is very easy & effective too,, 这个简单的代码也非常简单有效,

For a = 1 to lastrow 对于a = 1到lastrow

if cells(a,1) = "" then 如果单元格(a,1)=“”那么

goto lastline 转到最后一行

Here you can put your codes 在这里你可以把你的代码

lastline: lastLine所:

Next a 接下来a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM