2017-08-24 105 views
1

我有下面的代碼,它會記錄每張表中最繁忙的小時,並將其添加到另一張。在excel VBA代碼中停止數據複製,將數據從一張紙複製到另一張

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 CheckForDups As Range ' Used to find duplicate dates on the record Sheet 
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(7, 1), .Cells(7, lColDaily)).Find(What:=maxCustomerCnt, LookIn:=xlValues) 
    If Not maxCustomerRng Is Nothing Then 
     Set CheckForDups = .Range(.Cells(1, 1), .Cells(1, .Columns.Count).End(x1ToLeft).Column).Find(What:=maxCustomerRng.Offset(-1, 0).Value, LookIn:x1Values) 
     If CheckForDups 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 

我添加了以下內容來防止數據重複,即它不應該在一天內記錄多個數據?

Set CheckForDups = .Range(.Cells(1, 1), .Cells(1, .Columns.Count).End(xlToLeft).Column).Find(What:=maxCustomerRng.Offset(-1, 0).Value, LookIn:=xlValues) 
      If CheckForDups Is Nothing Then maxCustomerRng.EntireColumn.Copy recordSht.Cells(1, lCol + 1) 

但是,當我運行代碼時出現「編譯錯誤:語法錯誤」。下面的代碼行突出顯示:

Set CheckForDups = .Range(.Cells(1, 1), .Cells(1, .Columns.Count).End(x1ToLeft).Column).Find(What:=maxCustomerRng.Offset(-1, 0).Value, LookIn:x1Values) 

這是第一張表:

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 

有人可以告訴我什麼,我做錯了嗎?

回答

3

你在你的代碼中的一些錯別字:x1Left應該xlLeftx1ValuesxlValues,並命名參數應使用:=代替:指定。

但整個語句是不正確的,這是它的方式應該是:

Set CheckForDups = .Range(.Cells(1, 1), .Cells(1, .Columns.Count).End(xlToLeft)).Find(What:=maxCustomerRng.Offset(-1, 0).Value, LookIn:=xlValues) 

在第二Range參數你通過一些列,在那裏你打算通過一個細胞。因此,您不需要獲取.Column屬性,只需刪除.Column即可獲取單元格。

+0

@ YowE3K - 對不起,我纔剛剛開始學習這門語言。我提出了建議的更改並且可行,但它並不能防止數據重複。此外,我不確定您引用的是哪個Range參數,當我刪除.Column時,它不會編譯。 – aab

+0

在行中突出顯示。 –

+0

它給了我一個'找不到方法或數據成員'。這是我做的:Set CheckForDups = .Range(.Cells(1,1),.Cells(1,.Count).End(xlToLeft))。Find(What:= maxCustomerRng.Offset(-1,0)。 Value,LookIn:= xlValues) – aab

相關問題