簡體   English   中英

根據相鄰單元格中的條件將數據粘貼到范圍中的下一個空白單元格中

[英]Pasting data in next blank cell in range based on criteria in adjacent cell

我是使用VBA的初學者。

我想將值復制並粘貼到特定范圍內第一個空白單元格中的另一張紙上。

例如工作表1是總帳:

  • F14單元格包含文本(租金或現金,或應收帳款等)
  • 單元格K14包含借方金額。 單元格14包含貸方金額。

    我想使用下一個可用的單元格,根據F14中的文本,將K14或K15中的量復制並粘貼到工作表2中的特定范圍內。

如果它是“現金”,則范圍= sheet2 D1:D10。 如果是租金,則粘貼到范圍sheet2 D20:D30等。

任何幫助,將不勝感激。

我認為這是一些代碼,可以獲取范圍內的下一個可用空閑單元格

Sub capturedata()

Dim sheet1, sheet2 As Worksheet
Dim testValue As String
Dim cashRange, rentRange As Range

Set sheet1 = ActiveWorkbook.Sheets("Sheet1") ' general ledger
Set sheet2 = ActiveWorkbook.Sheets("sheet2")

testValue = sheet1.Range("F14") ' the cell with rent, cash, etc in it

'the ranges
Set cashRange = sheet2.Range("D1:D10")
Set rentRange = sheet2.Range("D20:D30")

Select Case testValue 'based on what is in "f14"
    Case "Rent"
        'paste from k14
        '****I believe the below is the part you're really concerned with***

        For Each cell In cashRange
            If cell.Value = "" Then 'first empty cell
                    cell.Value = sheet1.Range("k14") 'make this more dynamic with a for loop if needed
                Exit For
            End If
        Next cell
    Case "Cash"

        'paste from k15
        For Each cell In rentRange ' make into a function to avoid repeated code
            If cell.Value = "" Then 'first empty cell
                    cell.Value = sheet1.Range("k14")
                Exit For
            End If
        Next cell

    Case "Accounts Receivable"
       'add a for loop here  based on other criteria
    Case Else
    'case not met

End Select


End Sub

暫無
暫無

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

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