VBA代码选择最后3列的前3列INSTEAD

时间:2013-05-06 16:53:45

标签: vba range

我正在处理一个代码,该代码应该从与我创建的表的最后三行对应的列中获取值。它需要在这种形式下,因为数字是随机的。

我在第一张excel表中有一个表,其中包含不同的值。我计算有多少行和列。

然后我从第二张表中获取属于列Index的最后三个值。我将使用这些索引来构造一个代码,该代码将获取这些索引并识别它们在第一个Excel工作表中对应的列。那么,我想让它为我提取这些价值。

问题是它获得的三个FIRST值不会持续

我该如何解决这个问题?

Option Explicit
Option Base 1

Sub ThreeBest()
Dim i As Integer, j As Integer, N As Integer
Dim Valeurs As Integer

Dim nb_Cells As Integer
Dim nb_Actions As Integer


nb_Cells = Worksheets("Actions").Cells(Rows.Count, 2).End(xlUp).Row - 1
nb_Actions = Worksheets("Actions").Cells(1, Columns.Count).End(xlToLeft).Column - 1
N = 3 'We want to choose the three last ones

ReDim ValeursAction(nb_Cells) As Variant

For i = 1 To N
        Valeurs = Worksheets("Performance").Cells(nb_Actions + 7 - (i - 1), 9).Value
        'I place the value from the column corresponding to Valeurs in Performance
        For j = 1 To nb_Cells
            ValeursAction(j) = Worksheets("Actions").Cells(j + 1, Valeurs + 1)

        With Sheets("Performance")
                       .Cells(5 + j, 5 - i) = ValeursAction(j)
        End With
Next j
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

除非我完全误解了您的请求,否则我认为您需要使用xlToRight和xlDown分别查找最后的列和行。
试试这个:

Option Explicit
Option Base 1

Sub ThreeBest()
Dim i As Integer, j As Integer, N As Integer
Dim Valeurs As Integer

Dim nb_Cells As Integer
Dim nb_Actions As Integer


nb_Cells = Worksheets("Actions").Cells(Rows.Count, 2).End(xlDown).Row - 1
nb_Actions = Worksheets("Actions").Cells(1, Columns.Count).End(xlToRight).Column - 1
N = 3 'We want to choose the three last ones

ReDim ValeursAction(nb_Cells) As Variant

For i = 1 To N
        Valeurs = Worksheets("Performance").Cells(nb_Actions + 7 - (i - 1), 9).Value
        'I place the value from the column corresponding to Valeurs in Performance
        For j = 1 To nb_Cells
            ValeursAction(j) = Worksheets("Actions").Cells(j + 1, Valeurs + 1)

        With Sheets("Performance")
                       .Cells(5 + j, 5 - i) = ValeursAction(j)
        End With
Next j
Next i

End Sub