2)您正在查找最後一列,但在哪張表中?你必須完全符合這條道路。
If WorksheetFunction.CountA(Sheets("Sheet1").Cells) > 0 Then
LastCol = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
End If
同樣是Range
這是正確的做法之前
With Sheets("Sheet1")
Set DatesRange = Range("B2" & LastCol)
End With
你缺少一個DOT的情況下...
.Range("B2....
而且Range("B2" & LastCol)
不會放棄你想要的範圍。請參閱下面的代碼,瞭解如何創建您的範圍。
3)您正在使用變量LastColumn
,但使用的是LastCol
。我強烈建議使用Option Explicit
我也建議查看此鏈接(請參閱鏈接中的第2點)。
主題:以「錯誤」是人類
鏈接:http://www.siddharthrout.com/2011/08/01/to-err-is-human/
4)會發生什麼,如果有.CountA(Sheets("Sheet1").Cells) = 0
? :)我建議你這個代碼,而不是
If WorksheetFunction.CountA(Sheets("Sheet1").Cells) > 0 Then
LastCol = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Else
MsgBox "No Data Found"
Exit Sub
End If
5)ActiveSheet.Rows.Count
不會給你的最後一個活動行。它會給你該表中的總行數。我會建議獲取有數據的Col A的最後一行。
您可以使用此爲
With Sheets("Sheet")
LastRow =.Range("A" & .Rows.Count).End(xlup).row
End With
現在使用LastRow
代替ActiveSheet.Rows.Count
您可能還需要使用一個For Loop
,這樣你就不必增加每次i
。例如
For i = 1 to LastRow
6)最後,你不應該使用End
。原因很簡單。這就像使用POWER OFF按鈕切換您的計算機。 End語句突然停止代碼執行,而無需調用Unload,QueryUnload或Terminate事件或任何其他Visual Basic代碼。另外,其他程序保存的對象引用(如果有)也將失效。
7)根據您在Chat的形象,我相信您正在嘗試這麼做?這使用了一個不使用任何循環的代碼。
Option Explicit
Sub FindFill()
Dim wsI As Worksheet, wsO As Worksheet
Dim DatesRange As Range
Dim LastCol As Long, LastRow As Long
If Application.WorksheetFunction.CountA(Sheets("Sheet1").Cells) = 0 Then
MsgBox "No Data Found"
Exit Sub
End If
Set wsI = Sheets("Sheet1")
Set wsO = Sheets("Sheet2")
With wsI
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set DatesRange = .Range("B1:" & Split(Cells(, LastCol).Address, "$")(1) & 1)
.Columns(1).Copy wsO.Columns(1)
DatesRange.Copy
wsO.Range("B2").PasteSpecial xlPasteValues, _
xlPasteSpecialOperationNone, False, True
.Range("B2:" & Split(Cells(, LastCol).Address, "$")(1) & LastCol).Copy
wsO.Range("C2").PasteSpecial xlPasteValues
End With
End Sub
嗯。偉大的觀察。我確實解決了這個問題,但同樣的錯誤仍然存在。 – speci
錯誤發生時'i'和'LastCol'的值是多少? –
i = 1,LastCol是工作表中填充列的數量。 – speci