簡體   English   中英

Excel VBA循環到下一組文本,然后轉到第一個空白單元格並輸入文本字符串

[英]Excel VBA Loop to next group of text then go up to the first blank cell and enter text string

我對編碼世界很陌生。 我有一組單元格的行,其中包含文本,中間有兩行空行。 它們是2和3的組,位於A和B列。

對於每組文本,我需要轉到B列文本上方的最后一個空白單元格,然后輸入“從該組單元格A的頂行開始的文本string_text”。

我試着用這個:

Sub FindBlankAndFill()

    Dim cnter As Integer    
    firstRow = Cells(Rows.Count, 1).End(xlUp).Row
    cnter = 0

    For i = 2 To firstRow
        If IsEmpty(Cells(i, 1)) Then
            Select Case cnter
                Case 0: Cells(i, 2).Value = "Test Value"
                Case Else: Cells(i, 2).Value = ""
            End Select
            cnter = cnter + 1
        End If
    Next i

End Sub

這僅適用於第一組文本,然后將其他組完全留空。 上面的代碼也沒有這樣,它將拉取文本字符串所需的單元格值。

如果您有任何想法或解決方案,我將非常感謝您的幫助。 在After圖片中,黃色單元格是VBA應添加的單元格。 應該從該特定組的A列中的單元格中拉出“測試值”下划線之后的部分。

運行VBA之前的數據樣本

數據樣本運行VBA后

你的算法很接近。 基本上,您使用cnter變量來跟蹤遇到的空白行,因此當您找到更多數據時,需要重置該值。 你的firstRow語句真的找到了lastRow

Option Explicit

Sub FindBlankAndFill()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim cnter As Integer
    Dim i As Integer

    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    cnter = 0

    For i = lastRow To 1 Step -1
        If IsEmpty(ws.Cells(i, 1)) Then
            Select Case cnter
                Case 0:
                    '--- found the blank row above the data
                    ws.Cells(i, 2).Value = "Test Value_" & ws.Cells(i + 1, 1)
                    cnter = 1
                Case 1:
                    '--- found the blank row below the data,
                    '    so do nothing
            End Select
        Else
            '--- we found some data, so set the flag
            '    for when we find the next blank row
            cnter = 0
        End If
    Next i
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM