Excel VBA复制范围和单元格

时间:2017-10-16 13:43:15

标签: excel vba excel-vba

我正在尝试将数据从A表复制到表B中。

我想复制第X列第4行到第13行的一系列单元格(X =第13行最高值的单元格列,并将复制的值粘贴到第B行的第4行到第13行。 / p>

运行代码不会复制数据,我没有错误但没有粘贴任何内容。

有人可以看看代码,看看我的错误在哪里:

Sub Daily()
    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 Double ' value of highest customer count



    Set dailySht = ThisWorkbook.Sheets("Sheet A")
    Set recordSht = ThisWorkbook.Sheets("Sheet B")
    With recordSht
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).column
    End With
    With dailySht
        lColDaily = .Cells(1, .Columns.Count).End(xlToLeft).column
        maxCustomerCnt = Round(Application.Max(.Range(.Cells(13, 1), .Cells(13, lColDaily))), 2)
        Set maxCustomerRng = .Range(.Cells(13, 1), .Cells(13, lColDaily)).Find(What:=maxCustomerCnt, LookIn:=xlValues)
        If Not maxCustomerRng Is Nothing Then
        ' Check the Record Sheet to ensure the data is not already there
            Set CheckForDups = recordSht.Range(recordSht.Cells(13, 1), recordSht.Cells(13, lCol)).Find(What:=Round(maxCustomerRng.Value, 2), LookIn:=xlValues)
        ' If CheckForDups is Nothing then the date was not found on the record sheet. Therefore, copy the column
            If CheckForDups Is Nothing Then
                Range(Cells(4, maxCustomerRng), Cells(13, maxCustomerRng)).Copy
                recordSht.Cells(4, lCol + 1).PasteSpecial xlPasteValues
                recordSht.Cells(4, lCol + 1).PasteSpecial xlPasteFormats
            End If
        End If
    End With

    Set maxCustomerRng = Nothing
    Set dailySht = Nothing
    Set recordSht = Nothing
End Sub

2 个答案:

答案 0 :(得分:2)

您试图在一组未包含的数据中找到舍入值。 CheckForDups总是没有什么

答案 1 :(得分:0)

你有这个:

With dailySht

然后对ActiveSheet块中With的隐式引用:

Range(Cells(4, maxCustomerRng), Cells(13, maxCustomerRng)).Copy

这些隐式ActiveSheet引用使您的代码取决于当前处于活动状态的工作表,这可能不是您想要的 - FWIW Rubberduck(开源VBIDE)我管理的加载项项目可以帮助您轻松地在项目中的任何位置找到它们:

Rubberduck inspections

该解决方案可能会使用点限定这些调用,以便它们可以使用dailySht工作表对象:

.Range(.Cells(4, maxCustomerRng), .Cells(13, maxCustomerRng)).Copy