0

シートから名前を取得し(「名前」というシートでA2としましょう)、別のワークシートで同じ名前を検索します(「ジョブ」でA2と言います)。その名前が他のワークシートで見つかった後、そのすぐ隣のセルから値をコピーして(まだ「ジョブ」にありますが、B2)、最初のシートの別のセル(E2)に戻します(「名前」) 。最終的には、「名前」のA1のすべての値をループして、シート全体に入力したいと思います。

私はこれまでに得ました:

Sub fixThis()
    Dim i As Long, j As Long, col1 As Long, col2 As Long, lastrow1 As Long, lastrow2 As Long
    Dim sheetOne As String
    Dim sheetTwo As String

    col1 = 5
    col2 = 1
    sheetOne = "Names"
    sheetTwo = "Job"
    lastrow1 = Cells(Rows.Count, col1).End(xlUp).Row
    lastrow2 = Cells(Rows.Count, col2).End(xlUp).Row

    For i = 2 To lastrow1
        For j = 2 To lastrow2

           If sheetOne.Cells(i, col1).Value = sheetTwo.Cells(j, col2).Value Then

                sheetOne.Cells(i, 6).Value = sheetTwo.Cells(j, 2).Value

           End If
        Next
    Next
End Sub
4

1 に答える 1

2

シート名を文字列として保存しても問題ありません。ただし、これらを使用する場合は、次のようにシートオブジェクトを参照するために使用する必要があります。Sheets("Sheetname").Cells().Value または、次のような変数を使用できます。

Dim strSheet1name as String
strSheet1name = "Sheet1"

Sheets(strSheet1name).Cells().Value

最後に、本当に必要な場合は、次のような独自のシートオブジェクトを宣言できます。

Dim ws as worksheets
ws = Sheets("Sheet1")

ws.Cells.value

上記のすべてのコードを同じに保つには、置き換えてみる必要があります

       If sheetOne.Cells(i, col1).Value = sheetTwo.Cells(j, col2).Value Then

            sheetOne.Cells(i, 6).Value = sheetTwo.Cells(j, 2).Value

       End If

       If Sheets(sheetOne).Cells(i, col1).Value = Sheets(sheetTwo).Cells(j, col2).Value Then

            Sheets(sheetOne).Cells(i, 6).Value = Sheets(sheetTwo).Cells(j, 2).Value

       End If

最後に、複数のシートで作業している場合は、これらの行にさらに詳細を追加する必要があります。

lastrow1 = Cells(Rows.Count, col1).End(xlUp).Row
lastrow2 = Cells(Rows.Count, col2).End(xlUp).Row

そして、それらを次のようなものに変更します。

lastrow1 = Sheets(SheetOne).Cells(Sheets(SheetOne).Rows.Count, col1).End(xlUp).Row
lastrow2 = Sheets(SheetTwo).Cells(Sheets(SheetTwo).Rows.Count, col2).End(xlUp).Row

最終バージョンは次のようになります。

Sub fixThis()
    Dim i As Long, j As Long, col1 As Long, col2 As Long, lastrow1 As Long, lastrow2 As Long
    Dim sheetOne As String
    Dim sheetTwo As String

    col1 = 5
    col2 = 1
    sheetOne = "Names"
    sheetTwo = "Job"
    lastrow1 = Sheets(sheetOne).Cells(Sheets(sheetOne).Rows.Count, col1).End(xlUp).Row
    lastrow2 = Sheets(sheetTwo).Cells(Sheets(sheetTwo).Rows.Count, col2).End(xlUp).Row

    For i = 2 To lastrow1
        For j = 2 To lastrow2
            If Sheets(sheetOne).Cells(i, col1).Value = Sheets(sheetTwo).Cells(j, col2).Value Then
                Sheets(sheetOne).Cells(i, 6).Value = Sheets(sheetTwo).Cells(j, 2).Value
            End If
        Next j
    Next i
End Sub
于 2012-07-16T15:02:12.710 に答える