[英]VBA: object doesn't support this property or method
我写了一个非常简单的宏,它打开了另一个工作簿并从该工作簿中选择数据范围。 但是,我不断收到此警告:对象不支持此属性或方法
怎么了?
Sub data()
Dim wb As Workbook
Dim ws As Worksheet
Dim filename As String
Dim lastrow As Integer
Dim lastcolumn As Integer
Dim range_to_copy As Range
'open workbook
filename = "C:\Users\mk\Desktop\sales report\Sales Report.xls"
Set wb = Workbooks.Open(filename)
Set ws = wb.Sheets("data")
lastcolumn = wb.ws.Cells(1, wb.ws.Columns.Count).End(xlToLeft).Column
lastrow = wb.ws.Cells(wb.ws.Roows.Count, 1).End(xlToLeft).Row
range_to_copy = Range("Cells(1,1):Cells(lastrow,lastcolumn)")
End sub
许多事情错了。
编辑:
Dim lastrow As Integer Dim lastcolumn As Integer
一个Integer
最多可以存储32,767个数字。 对于列而言,这将不是问题,但会在行号上引发溢出错误。 最好使用Long
数据类型-数字最大为2147486647。
ws
变量已经引用了工作簿,因此您只需要:
lastcolumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
lastrow = wb.ws.Cells(wb.ws.Roows.Count, 1).End(xlToLeft).Row
Rows
只有一个o
。
编辑: xlToLeft
看着最右边的单元格并向左工作。 在查找行时,需要使用xlUp
来查看最后一个单元格并进行处理。
range_to_copy = Range("Cells(1,1):Cells(lastrow,lastcolumn)")
这是一个对象,因此必须对其进行Set
。 单元格引用由逗号分隔,不应保留为字符串。
Sub data()
Dim wb As Workbook
Dim ws As Worksheet
Dim filename As String
Dim lastrow As Long
Dim lastcolumn As Long
Dim range_to_copy As Range
'open workbook
filename = "C:\Users\mk\Desktop\sales report\Sales Report.xls"
Set wb = Workbooks.Open(filename)
Set ws = wb.Sheets("data")
lastcolumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
lastrow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Set range_to_copy = ws.Range(ws.Cells(1, 1), ws.Cells(lastrow, lastcolumn))
End Sub
注意:每个范围引用之前都有工作表引用。 否则,它将始终查看当前活动的工作表,因此,如果您不在data
表中,则以下操作将失败,因为第二个单元格引用将查看活动的工作表。
ws.Range(ws.Cells(1, 1), Cells(lastrow, lastcolumn))
可能值得检查With....End With
代码块。
您的代码中有几个错误。 尝试
lastcolumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Set range_to_copy = Range(ws.Cells(1, 1), ws.Cells(lastRow, lastcolumn))
一旦定义并设置了ws
工作表对象,就不再需要引用wb
对象,因为ws
工作表对象在wb
工作簿中完全被Sheets("data")
修饰了。
现在,您需要做的就是使用With
语句,如下面的代码所示:
Set ws = wb.Sheets("data")
With ws
lastcolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set range_to_copy = .Range(.Cells(1, 1), .Cells(lastrow, lastcolumn))
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.