从其他选项卡值填充电子表格

时间:2017-01-11 16:33:33

标签: excel vba excel-vba

在Excel for Mac中:

我有2个标签(wkst1和wkst2),需要填充第三个标签(wkst3)

wkst1有一列列出了名字 e.g。

A

B

wkst2有两列

X     1

Y     4

我需要填充wkst3以确保wkst2中的所有行都与wkst1中列出的每个名称相关联。

e.g。我希望的结果是:

A     X     1

A     Y     4

B     X     1

B     Y     4

你能建议我应该使用的代码吗?

1 个答案:

答案 0 :(得分:0)

我设法自己解决了这个问题。

Sub writeall()

    Dim Ws As Worksheet
    Dim Ws1 As Worksheet
    Dim Ws2 As Worksheet

    Dim X As Long
    Dim Y As Long
    Dim count As Long

    Application.ScreenUpdating = False

    Set Ws = ActiveWorkbook.Worksheets(1)
    Set Ws1 = ActiveWorkbook.Worksheets(2)
    Set Ws2 = Workbooks("xxxx.xlsx").Sheets("2017") ' xxxx is the name of the xlsx

    count = 1

    For X = 2 To Ws2.Range("A" & Rows.count).End(xlUp).Row
        For Y = 1 To Ws1.Range("A" & Rows.count).End(xlUp).Row
            count = count + 1
            Ws.Cells(count, 1).Value = Ws2.Cells(X, 1).Value
            Ws.Cells(count, 2).Value = Ws1.Cells(Y, 2).Value
            Ws.Cells(count, 3).Value = Ws1.Cells(Y, 1).Value

        Next Y
    Next X

    Application.ScreenUpdating = True
    MsgBox ("Spreadsheet updated")

End Sub