【问题标题】:Excel VBA copy range and cellsExcel VBA 复制范围和单元格
【发布时间】:2017-10-16 13:43:15
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您是否尝试过单步执行代码(使用 F8)?我的猜测是你有两个或最初的 if 语句给出一个错误,它结束了语句。有助于缩小问题范围,还可以让您查看为每个变量提取了哪些值。
  • @Cyril 实际上,在复制整个列时,代码可以正常工作。我正在尝试修改它以仅复制特定的单元格,这就是我遇到问题的地方。所以我认为问题在于复制/粘贴功能。你怎么看?

标签: vba excel


【解决方案1】:

您正试图在一组未舍入的数据中找到一个舍入值。 CheckForDups 什么都不是

【讨论】:

  • 我认为问题在于复制和粘贴功能。复制整个列而不是特定单元格时,代码运行良好。
【解决方案2】:

你有这个:

With dailySht

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

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

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

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

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

【讨论】:

  • 谢谢,但代码链接到 recordSht 按钮上的按钮,所以我猜这应该不是问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多