簡體   English   中英

如何檢查跨列的值,然后復制其下一個單元格的內容?

[英]How to check for a value across columns and then copy the the contents of one cell below it?

因此,我有一張Excel工作表,該工作日的星期幾從D7開始,並在每月15天擴展到AF7。 我想瀏覽每一個,然后將第8行中它們正下方的單元格的內容復制到另一張紙上。

我在運行時錯誤1004對象_Global的方法范圍在此行上失敗。 我對VBA還是很陌生,所以我不確定到底出了什么問題。

LastCol = Range(Cells(7, Columns.Count)).End(xlUp).Columns

完整代碼:

Sub Copy()
    Dim cell As Range
    Dim lastRow As Long, i As Long

    LastCol = Range(Cells(7, Columns.Count)).End(xlUp).Columns
    i = 4

    For Each cell In Sheets(1).Range(LastCol & "D7:7")
        If cell.Value = "MON" Then
            cell.Offset(-1, 0).Copy Sheets(2).Cells(1, i)
            i = i + 1
        End If
    Next

End Sub

要獲取最后一行,即最右邊的一行,請首先將MyRow設置為要使用的行:

lastcol= ActiveSheet.Cells(MyRow, Columns.Count).End(xlToLeft).Column

對於最后一行,將MyColumn設置為適當的值后:

lastrow = ActiveSheet.Cells(Rows.Count, MyColumn).End(xlUp).Row

但是您的范圍參考也不完全正確。 就個人而言,我看不到在循環中使用范圍變量的價值。 你可以試試看。 (請注意,負偏移量讀取的是上面的行,而不是下面的行)

Sub Copy()
Dim lastRow As Long, i As Long, LocX as long
Dim source As Worksheet, dest As Worksheet
Set source = Sheets(1)
Set dest = Sheets(2)
lastcol = source.Cells(7, Columns.Count).End(xlToLeft).Column
i = 4
For locX = 4 To lastcol
    If source.Cells(7, locX).Value = "mon" Then
        source.Cells(7, locX).Offset(1, 0).Copy dest.Cells(1, i)
        i = i + 1
    End If
Next
End Sub

您分配給LastCol的名稱似乎表明您要獲取列號,但您使用的是xlUp而不是xlToLeft 另外,您要的是.Columns而不是Column

LastCol = Cells(7, Columns.Count).End(xlToLeft).Column

這將返回第7行中最后使用的列的列號(例如F列為6,AA列為27等)。

with Sheets(1)
    LastCol = .Cells(7, Columns.Count).End(xlToLeft).Column
    For Each cell In .cells(7, "D").resize(1, LastCol - 3)
        If ucase(cell.Value) = "MON" Then
            cell.Offset(1, 0).Copy destination:=Sheets(2).Cells(1, i)
            i = i + 1
        End If
    Next
end with
  1. 您是否在第7行中使用自定義數字格式ddd的實際日期? 如果是這種情況,那么您應該使用If weekday(cell.Value) = 2 Then代替檢查MON
  2. 如果要在單元格的正下方復制單元格的內容,則偏移量應為1行而不是-1行; 例如cell.Offset(1, 0).Copy

暫無
暫無

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

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