Excel VBA代码将数据从一张表复制到另一张

我试图达到以下目的:

  • logging每天最繁忙的时间(即客户数量最多),并将其详细信息(客户数量,花费金额,平均花费时间)logging到第二个电子表格中。
  • 在第二个电子表格上,每次都会添加一个新列。 它只会logging每天最繁忙的时间。

    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':每当我运行代码(它被附加到第二个工作表上的一个button)上的下一行object'_Worksheet失败的方法'范围'。

 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 

有人可以帮我弄清楚代码有什么问题吗?

代替

 .Range(Cells(2, 1), Cells(2, lColDaily)) 

尝试

 .Range(.Cells(2, 1), .Cells(2, lColDaily)) 

Mrigs的评论是正确的,使用.Range(.Cells(2, 1), .Cells(2, lColDaily))

就像解释一样(因为错误是如此普遍): cells (没有前导点)是指活动表单。 .cells (带点)在你的情况下是指with -statement的表格,你可以写dailySht.cells来代替。

因此,在您的声明中,您要求活动工作表(这很可能是一张不同的工作表)中的单元格定义的工作表的范围,这是不可能的,并引发您所看到的错误。