2013-04-30 99 views
0

我需要找出在一個範圍內的最後一列是與定義的列最後一欄有activecell查找指定的範圍

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange 
+2

'RngSource.Columns(RngSource.Columns.Count).Column' – NickSlash 2013-04-30 21:26:14

+0

見[此](http://www.siddharthrout.com/2012/11/09/find-last- excel-sheet-vbavb-net /) – 2013-04-30 21:28:19

回答

0

使用結束(xlToRight)。

+1

這是錯誤的做法:)想象一下,如果Activecell位於最後一列? – 2013-04-30 21:30:30

+0

優秀點...我總是忘記'查找'。感謝您將此引起我的注意。 – Marshall 2013-04-30 21:44:13

1

第一

第一件事不要使用UsedRange來設置範圍。我已經解釋過HERE,爲什麼你不應該使用UsedRange

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange 

查找最後一列有數據和最後一行其中有數據,然後設置你的範圍。所以你不會出現從範圍中找到最後一列的問題。下面是一個例子

Sub Sample() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim lRow As Long, lCol As Long 

    '~~> Set your worksheet 
    Set ws = ThisWorkbook.Sheets("Sheet1") 

    With ws 
     If Application.WorksheetFunction.CountA(.Cells) <> 0 Then 
      '~~> Find Last Row 
      lRow = .Cells.Find(What:="*", _ 
          After:=.Range("A1"), _ 
          Lookat:=xlPart, _ 
          LookIn:=xlFormulas, _ 
          SearchOrder:=xlByRows, _ 
          SearchDirection:=xlPrevious, _ 
          MatchCase:=False).Row 

      '~~> Find Last Column 
      lCol = .Cells.Find(What:="*", _ 
        After:=.Range("A1"), _ 
        Lookat:=xlPart, _ 
        LookIn:=xlFormulas, _ 
        SearchOrder:=xlByColumns, _ 
        SearchDirection:=xlPrevious, _ 
        MatchCase:=False).Column 
     Else 
      lRow = 1: lCol = 1 
     End If 

     '~~> Set your range 
     Set rng = .Range(.Cells(1, 1), .Cells(lRow, lCol)) 

     Debug.Print rng.Address 
    End With 
End Sub