0

同じExcelファイル内に2つのデータシートがあります.シート1は7列の「データ」として: ここに画像の説明を入力

2 番目のシートは「メイン」で、5 つの列があります。 ここに画像の説明を入力

2 つのファイルに一致する同じ列は「名前」です。両方のシートの名前に一致するVBAコードが必要で、両方のシートの列名を一致させることにより、シート「メイン」からシート「データ」にproc1 - Proc4からデータをコピーします。

同様の質問についてスタックオーバーフローを検索しましたが、見つけたコードは次のとおりです(少し変更しました):

Sub CopyData()

Dim shtImport As Worksheet
Dim shtMain As Worksheet
Set shtImport = ThisWorkbook.Sheets("Data")
Set shtMain = ThisWorkbook.Sheets("Main")

    Dim CopyColumn As Long
    Dim CopyRow As Long
    Dim LastColumn As Long

    '- for each column in row 1 of import sheet
    For CopyColumn = 1 To shtImport.Cells(1, shtImport.Columns.Count).End(xlToRight).Column
    '- check what the last column is with data in column
    LastRowOfColumn = shtImport.Cells(shtImport.Columns.Count, CopyColumn).End(xlToRight).Column
    'if last column was larger than one then we will loop through rows and copy
    If LastColumn > 1 Then
    For CopyRow = 1 To LastColumn
    '- note we are copying to the corresponding cell address, this can be modified.
    shtMain.Cells(CopyRow, CopyColumn).value = shtImport.Cells(CopyRow, CopyColumn).value
    Next CopyRow
    End If
    Next CopyColumn

    End Sub

これは、私が望むように機能していません。誰かがこの問題を手伝ってくれませんか。どうもありがとう!

4

1 に答える 1

0

このコードを試してください:

Sub CopyData()

Dim shtImport As Worksheet
Dim shtMain As Worksheet
Set shtImport = ThisWorkbook.Sheets("Data")
Set shtMain = ThisWorkbook.Sheets("Main")

'From Main to Data
Dim rngImpTitles As Range
Set rngImpTitles = shtImport.Rows(1)
Dim rngImpNames As Range
Set rngImpNames = shtImport.Columns(1)

Dim CopyColumn As Long
Dim CopyRow As Long
Dim foundRow As Long
Dim foundCol As Long

On Error Resume Next
'for each column in row 1 of import sheet
For CopyColumn = 2 To shtMain.Cells(1, shtMain.Columns.Count).End(xlToLeft).Column
    foundCol = rngImpTitles.Find(shtMain.Cells(1, CopyColumn).Value2).Column
    If Err.Number <> 0 Then
        MsgBox "Not such a col title in importsheet for " & vbNewLine & _
                        shtMain.Cells(1, CopyColumn)
        Err.Clear
        GoTo skip_title
    End If


    For CopyRow = 2 To shtMain.Cells(shtMain.Rows.Count, 1).End(xlUp).Row
        foundRow = rngImpNames.Find(shtMain.Cells(CopyRow, 1)).Row
        If Err.Number <> 0 Then
            MsgBox "Not such a row name in importsheet for " & vbNewLine & _
                        shtMain.Cells(CopyRow, 1)
            Err.Clear
            GoTo skip_row
        End If

            If Len(shtMain.Cells(CopyRow, CopyColumn)) <> 0 Then
                    shtMain.Cells(CopyRow, CopyColumn).Copy shtImport.Cells(foundRow, foundCol)
            End If

skip_row:
    Next CopyRow
skip_title:
Next CopyColumn

End Sub
于 2013-04-04T17:33:09.217 に答える