我正在努力实现以下目标:
在第二个电子表格中,每次都会添加一个新列。它只会记录每天最繁忙的小时。
Sub DailySales()
Dim dailySht As Worksheet 'worksheet storing latest store activity
Dim recordSht As Worksheet 'worksheet to store the highest period of each Day
Dim lColDaily As Integer ' Last column of data in the store activity sheet
Dim lCol As Integer ' Last column of data in the record sheet
Dim maxCustomerRng As Range ' Cell containing the highest number of customers
Dim maxCustomerCnt As Long ' value of highest customer count
Set dailySht = ThisWorkbook.Sheets("Supermarket Data")
Set recordSht = ThisWorkbook.Sheets("Record Data")
With recordSht
lCol = .Cells(1, .Columns.Count).End(xlToLeft).column
End With
With dailySht
lColDaily = .Cells(1, .Columns.Count).End(xlToLeft).column
maxCustomerCnt = Application.Max(.Range(Cells(2, 1), Cells(2, lColDaily)))
Set maxCustomerRng = .Range(.Cells(2, 1), .Cells(2, lColDaily)).Find(What:=maxCustomerCnt, LookIn:=xlValues)
If Not maxCustomerRng Is Nothing Then
maxCustomerRng.EntireColumn.Copy recordSht.Cells(1, lCol + 1)
End If
End With
Set maxCustomerRng = Nothing
Set dailySht = Nothing
Set recordSht = Nothing
End Sub
每次运行代码时,我得到一个“运行时错误'1004':对象'_工作表'的方法'范围'在以下行中失败”(它附加到第二个工作表上的按钮)。
maxCustomerCnt = Application.Max(.Range(Cells(2, 1), Cells(2, lColDaily)))
这是表格:
Customer data 7:00:00 AM 7:30:00 AM 8:00:00 AM 8:30:00 AM 9:00:00 AM
Number of customers 33 37 110 250 84
Amount spent 65 50 70 85 60
Average time spent 12 10 8 17 10
有人可以帮我弄清楚代码有什么问题吗?
答案 0 :(得分:4)
而不是
.Range(Cells(2, 1), Cells(2, lColDaily))
尝试
.Range(.Cells(2, 1), .Cells(2, lColDaily))
答案 1 :(得分:1)
Mrigs评论是对的,使用.Range(.Cells(2, 1), .Cells(2, lColDaily))
正如解释(因为错误如此常见):cells
(没有前导点)指的是活动表。您的案例中的.cells
(带点)是指with
- 语句的工作表,您可以改为编写dailySht.cells
。
因此,在您的陈述中,您要求工作表dailySht
的范围由活动工作表中的单元格定义(很可能是不同的工作表),这是不可能的并且会引发您看到的错误