如何将特定单元格从其他工作表复制/粘贴到当前工作表?

时间:2016-08-08 10:49:06

标签: excel vba excel-vba

我使用此代码使用用户名搜索来自多个交易的所有关联信息。然后应将它们粘贴到当前工作表中。它似乎运行,因为它不会抛出任何错误,它会执行最终的" Select"命令,但它不会返回任何粘贴的数据。

 try
    {
        $vies = new SoapClient('http://www.webservicex.com/spc/globalweather.asmx?wsdl', array('exceptions'=>true));
        var_dump($vies);
    }
    catch(SoapFault $e){
        $return_value = 'VAT check service is not available.';
        return $return_value;
    }

1 个答案:

答案 0 :(得分:0)

这是正确引用工作表的代码:

Option Explicit

Sub InvestorReport()
    Dim investorname As String
    Dim finalrow As Long
    Dim i As Long 'row counter

    With Sheets("Sheet001") '<--| refer to "Sheet1" sheet
        .Range("D6:K50").ClearContents '<--| with every initial "dot" you keep referencing the object after the "With" keyword ("Sheet1" sheet, in this case)
        investorname = .Range("B3").value
    End With

    With Sheets("Investments") '<--| refer to "Investments" sheet
        finalrow = .Cells(.Rows.Count, "I").End(xlUp).row '<--| .Cells and .Rows refer to "Investments" sheet
        For i = 2 To finalrow
            If .Cells(i, 1) = investorname Then
                .Range(.Cells(i, 2), .Cells(i, 12)).Copy '<--| .Range and .Cells refer to "Investments" sheet
                Sheets("Sheet001").Range("D100").End(xlUp).Offset(1, 0).PasteSpecial '<--| here all references are explicitly made to "Sheet1" sheet
            End If
        Next i
    End With

    Sheets("Sheet001").Range("B3").Select
End Sub

以下是避免循环和利用Autofilter的代码:

Sub InvestorReport2()
    Dim investorname As String
    Dim finalrow As Long
    Dim i As Long 'row counter

    With Sheets("Sheet001") '<--| refer to "Sheet1" sheet
        .Range("D6:K50").ClearContents '<--| with every initial "dot" you keep referencing the object after the "With" keyword ("Sheet1" sheet, in this case)
        investorname = .Range("B3").value
    End With

    With Sheets("Investments") '<--| refer to "Investments" sheet
        With .Range("A1", .Cells(.Rows.Count, "L").End(xlUp)) '<--| refer to "Investments" sheet columns A to I fom row 1 (header) down to last non empty one in column I
            .AutoFilter field:=1, Criteria1:=investorname '<--| filter data on first column values matching "investorname"
            If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any cell has been filtered...
                .Offset(1, 1).Resize(.Rows.Count - 1, .Columns.Count - 1).SpecialCells(xlCellTypeVisible).Copy '<--| ... copy filtered cells skipping headers and first column...
                Sheets("Sheet001").Range("D100").End(xlUp).Offset(1, 0).PasteSpecial '<--| ...and paste them
            End If
        End With
        .AutoFilterMode = False '<--| .. show all rows back...
    End With

    Sheets("Sheet001").Range("B3").Select
End Sub