2016-06-08 104 views
0

如何在電子表格中的數據最後一個單元格旁邊的列中指定單元格,例如如果我在在vba中定義動態範圍

Range(Cells(1, 1), Cells(lastRow, lastColumn)) 

有數據如何動態地定義

Range(Cells(1, 2), Cells(lastRow, n_lastColumn)) 

在功能,使得n_lastColumn指下一列lastColumn後?

回答

1

Range(Cells(1,1), Cells(lastRow, lastColumn)).offset(,1)

Range("A1").currentregion.offset(,1)

+0

請注意,如果您有稀疏的數據,「CurrentRegion」將停在空行/列處,這可能會導致不良行爲。 – arcadeprecinct

0

您可以使用對象上提供的UsedRange屬性。

但是請注意,這給你一個水印使用的範圍,而不是目前使用的範圍;即如果您在單元格中寫入值,則將其刪除,但仍然包含UsedRange

+0

看來,當你在一個宏用它來更新'UsedRange'。經過一些測試後,我發現它不可靠。在某些時候,它會調整列而不是行,並保留包含從未填充過的單元格。 – arcadeprecinct

0
sub find_last() 

    Dim LastRow As Integer 
    Dim LastCol As Integer 
    Dim WS as Worksheet 

    Set WS = ThisWorkbook.Worksheets("MySheet") 


    LastRow = WS.Cells.Find(What:="*", After:=WS.Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False, MatchByte:=False).row 
    LastCol = WS.Cells.Find(What:="*", After:=WS.Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False, MatchByte:=False).Column 


    WS.Cells(LastRow, LastCol + 1) = "MyData" 

end sub