如何将宏应用于整个列?

时间:2018-10-29 19:07:00

标签: excel vba excel-vba

我正在尝试将一个工作簿中的数据与另一个工作簿进行匹配。我正在进行一个for循环,但我想不出如何在不弄乱原始循环的情况下循环遍历整个列。

请帮助!

这是我当前的代码,我需要在每个要获取其数据的单元格上运行代码:

Sub SKU_Match()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:=Application.GetOpenFilename)
wb.Activate

Dim sh As String
sh = wb.Worksheets(1).Name
Dim lastRow As Integer
Row1 = ActiveSheet.UsedRange.Rows.Count

Dim index(1 To 1000, 1 To 2) As String
Dim i As Variant, j As Integer

For i = 1 To 1000
   For j = 1 To 2
        If j = 1 Then
           index(i, j) = wb.Worksheets(sh).Cells(i, 4).Value
        ElseIf j = 2 Then
            index(i, j) = wb.Worksheets(sh).Cells(i, 10).Value
        End If
    Next j
Next i

wb.Close

For i = 1 To Row1
    If index(i, 1) = Range("A" & (ActiveCell.Row)).Value 
Then
        ActiveCell.Value = index(i, 2)
    End If
Next i


End Sub 

我已经尝试过以这种方式循环,但是这只会在所有行中输入活动单元格的数据,而无需将宏分别应用于每行:

Sub SKU_Match()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:=Application.GetOpenFilename)
wb.Activate

Dim sh As String
sh = wb.Worksheets(1).Name
Dim lastRow As Integer
Row1 = ActiveSheet.UsedRange.Rows.Count

Dim index(1 To 1000, 1 To 2) As String
Dim i As Variant, j As Integer

For i = 1 To 1000
   For j = 1 To 2
        If j = 1 Then
           index(i, j) = wb.Worksheets(sh).Cells(i, 4).Value
        ElseIf j = 2 Then
            index(i, j) = wb.Worksheets(sh).Cells(i, 10).Value
        End If
    Next j
Next i

wb.Close
For k = 0 to 58
    For i = 1 To Row1
        If index(i, 1) = Range("A" & (ActiveCell.Row)).Value 
    Then
             ActiveCell.Offset(k,0).Value = index(i, 2)
        End If
    Next i
Next k


End Sub

1 个答案:

答案 0 :(得分:0)

该解决方案基于以下假设:找到的每个匹配值将添加到与SKU对应的行中的工作表中,并且每个找到的匹配将增加列偏移量。另外,我认为不需要将wb的值存储在数组中,可以直接从wb中提取。即使接近您的目标,也可以随时提出。

Sub SKU_Match2()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:=Application.GetOpenFilename)
Dim sh As String
sh = wb.Worksheets(1).Name
Dim lastRow As Integer

ThisWorkbook.Activate
Row1 = ActiveSheet.UsedRange.Rows.Count


For i = 1 To Row1
K = 1   'Assumtion: offset column kept 0 and will be incremented for each found
    ValToMatch = ThisWorkbook.ActiveSheet.Range("A" & i).Value
        For j = 1 To 1000
        MatchVal = wb.Worksheets(sh).Cells(j, 4).Value
        ValtoAdd = wb.Worksheets(sh).Cells(j, 10).Value
            If MatchVal = ValToMatch Then
            K = K + 1   'Assumtion: each value of the match found will added to the worksheet in the
            'row corresponding to SKU and column offset will increment for each match found
            ThisWorkbook.ActiveSheet.Cells(i, K).Value = ValtoAdd
            End If
         Next j
Next i
wb.Close False
End Sub