Excel 自动将VBA中的范围调整为第一个空列

Excel 自动将VBA中的范围调整为第一个空列,excel,vba,Excel,Vba,我有以下Excel电子表格: A B C D E F 1 2019-03 2019-04 2019-05 2019-06 2019-07 2 3 Revenue 500 600 4 COGS -40 -30 5 Gross Profit

我有以下Excel电子表格:

       A                 B         C         D        E          F
1                     2019-03   2019-04   2019-05   2019-06   2019-07
2    
3   Revenue             500       600
4   COGS                -40       -30
5   Gross Profit        460       570
6   
7   OPEX                -10       -12
8   Interests           -20       -50
9
8   EBT                 430       508
公式:

B5 = SUM(B3:B4)
C5 = SUM(C3:C4)
B10 = B5+B7+B8
C10 = C5+C7+C8
电子表格显示了公司每月的绩效

每次到达新月份时,我都希望将上个月的值复制到新月份。因此,我为2019-05月制定了以下
VBA

Sub test()
Sheet1.Range("C5:C14").Copy
Sheet1.Range("D5:D14").PasteSpecial
End Sub
到目前为止,所有这些都很有效


现在我的问题是,我必须每月手动调整VBA中的范围,以复制上个月的值

因此,我想知道是否有办法告诉VBA哪个月是最后一个非空月,然后将本月的值/公式复制到下一个月。

您可以用下面的代码找到行中最后使用的列

Sub Last_Used_Column()
'Find the last used column in a Row: row 1 in this example
    Dim LastCol As Long
    With ActiveSheet
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With
    MsgBox LastCol
End Sub

您可以在代码中附加上述代码,并在需要的任何位置使用LastCol变量。

您可以使用以下代码找到行中最后使用的列

Sub Last_Used_Column()
'Find the last used column in a Row: row 1 in this example
    Dim LastCol As Long
    With ActiveSheet
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With
    MsgBox LastCol
End Sub
您可以在代码中附加上述代码,并在需要时使用LastCol变量。

类似的方法

Sub test()

Dim c As Long

With Sheet1
    c = .Cells(5, Columns.Count).End(xlToLeft).Column 'returns 3 if last column is C
    With Range(.Cells(5, c), .Cells(14, c))
        .Copy .Offset(, 1)
    End With
End With

End Sub
类似方法

Sub test()

Dim c As Long

With Sheet1
    c = .Cells(5, Columns.Count).End(xlToLeft).Column 'returns 3 if last column is C
    With Range(.Cells(5, c), .Cells(14, c))
        .Copy .Offset(, 1)
    End With
End With

End Sub

Sheet1.cells(5,columns.count).end(xltoleft).column
将给出第5行中最后使用的列,这样您就可以使用
单元格(r,c)
符号来引用正确的范围。
Sheet1.cells(5,columns.count).end(xltoleft).column
将给出第5行中最后使用的列,这样您就可以使用
单元格(r,c)
表示正确的范围。请注意,
.Column
返回的是
Long
而不是
整数。因此,请注意,
.Column
返回的是
Long
而不是
整数。前
Dim LastCol尽可能长