代码清楚地打开工作簿和工作表(带有四行数据)....但随后在“Lastrow = Cells .....”中STOPS,错误91“对象变量或未设置块变量。”
Dim Lastrow As Long, NumPickups As Integer
Workbooks.Open Filename:="C:\Users\dads\Downloads\Donation Data.xlsm"
Worksheets("DonationDataQuery").Activate
Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
NumPickups = Lastrow - 1
Range(Cells(1, 1), Cells(Lastrow, 22)).Select
Selection.Copy
Windows("test.xlsm").Activate
Range("J1").Select
ActiveSheet.Paste
Windows("Donation Data.xlsm").Activate
基于以下评论的修订代码方法:
Private Sub GeneratePickupData_Click()
'Open the Donation Data.xlsm and copy the data to this worksheet
Workbooks.Open Filename:="C:\Users\dads\Downloads\Donation Data.xlsm"
Worksheets("DonationDataQuery").Activate
'covert numbers brought over by Acess as text to numbers
Range("A1:O50").Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
Dim Lastrow As Long, NumPickups As Integer
Lastrow = 0
NumPickups = 0
''Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
Lastrow = Range("A1").End(xlDown).Row
NumPickups = Lastrow - 1
'Range(Cells(1, 1), Cells(Lastrow, 22)).Select
Range("A1", Range("A1").SpecialCells(xlLastCell)).Select
Range("A1:V50").Select
Selection.Copy
Windows("Pickup Form Gen 2.xlsm").Activate
Range("J1").Select
ActiveSheet.Paste
Windows("Donation Data.xlsm").Activate
ActiveSheet.UsedRange.ClearContents
ActiveWorkbook.Save
ActiveWindow.Close
答案 0 :(得分:0)
如果您的工作表中不包含带有“*”的单元格,Cells.Find("*", [A1], , , xlByRows, xlPrevious)
将为空。如果您再引用.Row
,则会收到您所描述的错误。
您似乎正在尝试查找工作表中最后填充的行。下面的代码将为您提供内容为“A”的列中的最后一行:
LastRow = Range("A1").End(xlDown).Row
请注意,如果您要选择工作表中的所有项目,这将为您提供包含所有已填充单元格的范围:
Dim allCells As Range
Set allCells = Range("A1", Range("A1").SpecialCells(xlLastCell))
这两段代码都是通过录制宏,选择单元格“A1”,然后按 Ctrl + 向下和 Ctrl 创建的。分别为+ Shift + End 。录制宏是启动任何vba函数的好方法!
答案 1 :(得分:0)
根据您的错误,我假设您的代码位于工作表代码模块中,因此除非使用工作表对象限定,否则所有Range和Cells调用都会引用该工作表。试试这个:
Dim Lastrow As Long
Dim NumPickups As Long
Dim rFound As Range
With Workbooks.Open(Filename:="C:\Users\dads\Downloads\Donation Data.xlsm").Worksheets("DonationDataQuery")
Set rFound = .Cells.Find("*", .Range("A1"), , , xlByRows, xlPrevious)
If rFound Is Nothing Then
Lastrow = 2
Else
Lastrow = rFound.Row
End If
NumPickups = Lastrow - 1
.Range(.Cells(1, 1), .Cells(Lastrow, 22)).Copy Destination:=Workbooks("test.xlsm").ActiveSheet.Range("J1")
End With