excel vba - 通过行/列地址间接复制?

时间:2017-07-19 07:15:09

标签: excel vba excel-vba

我有一张包含调查数据的工作表,其中每列包含一项调查。我现在希望复制当前评论的调查的特定单元格并将其粘贴到稍后将附加到电子邮件中的格式。下面的代码是计算正在审查的调查的当前列号,然后尝试复制该列中的特定单元格,但是,没有数据粘贴到该格式中。

以下代码:

Sub test
Dim dataSheet, dataStart, dataSurvey As Range
    dataSheet = "MED-FB-YTD"                                                    ' name of the sheet where data is stored
    Set dataSurvey = ThisWorkbook.Sheets("HeartBeat_Alert").Range("K5")         ' survey number of specific record  eg. 5
    Set dataStart = ThisWorkbook.Sheets("HeartBeat_Alert").Range("K4")          ' column number of first survey of specified time period    eg. 307
    dataCol = dataSurvey + dataStart - 1                                        ' actual data column is (dataStart + dataSurvey) - 1        eg. = 5+307-1 = column 311


    With ThisWorkbook.Sheets("HeartBeat_Alert")
        .Select
        Sheets(dataSheet).Cells(25, dataCol) = ActiveSheet.Range("B3").Value      ' copy room no
        Sheets(dataSheet).Cells(16, dataCol) = ActiveSheet.Range("B4").Value      ' copy arrival date
        Sheets(dataSheet).Cells(17, dataCol) = ActiveSheet.Range("B5").Value      ' copy departure date
    end with

end sub

在我看来,我试图复制数据的方式不起作用/支持,因此会感谢一些帮助。

谢谢, A2K

1 个答案:

答案 0 :(得分:1)

首先:dataSheet应该是String,而不是Range对象。

您可以省略dataSurveydataStart的声明并使用它(不会影响任何内容,因此您不必这样做):

dataCol = Sheets("HeartBeat_Alert").Cells(5, 11).Value - Sheets("HeartBeat_Alert").Cells(4, 11).Value

另一件事。如果您没有Select表(“HeartBeat_Alert”),那么请不要只使用.Cells(3, 2).Value代替ActiveSheet.Range("B3").Value(它也不应该影响结果,但它效率更高。)

完成这些更改后,它应该可以正常工作。