Hlookup填充151x499表,其中包含两个变量范围

时间:2015-07-27 04:22:32

标签: excel vba excel-vba

我希望此Hlookup填写151x499表。我的问题是随着每个循环计算x和y变量。我希望x对于所有499 y值都是2-152。

这是我到目前为止所写的:

Sub HlooksforRun()

Dim x As Integer
Dim y As Integer
For x = 2 To 152
For y = 2 To 500

ThisWorkbook.Worksheets("info for run").Select

Cells(x, y) = Application.WorksheetFunction.HLookup(Range("B1"), _
  Worksheets("Ranks (Standard Form)").Range("A1:SH152"), x, False)

Next x
Next y

End Sub

2 个答案:

答案 0 :(得分:0)

试试这个:

Sub HlooksforRun()

Dim x As Integer
Dim y As Integer
Dim rankSheet As Worksheet
Dim infoSheet As Worksheet
Dim myRange As Range

Set infoSheet = Sheets("info for run")
Set rankSheet = Sheets("Ranks (Standard Form)")
Set myRange = rankSheet.Range("B2:SH152")

For x = 2 To 152
    For y = 2 To 500
        ThisWorkbook.Worksheets("info for run").Activate
        infoSheet.Cells(x, y).Select
        ActiveCell.Value = Application.WorksheetFunction.HLookup(infoSheet.Range("B2"), myRange, x, False)
    Next y
Next x

End Sub

编辑:也许这更符合您的要求(这会将HLookup公式放入循环中指定的每个单元格中):

Sub HlooksforRun()

Dim x As Integer
Dim y As Integer
Dim rankSheet As Worksheet
Dim infoSheet As Worksheet
Dim myRange As Range

Set infoSheet = Sheets("info for run")
Set rankSheet = Sheets("Ranks (Standard Form)")
Set myRange = rankSheet.Range("B2:SH152")

For x = 2 To 152
    For y = 2 To 500
        ThisWorkbook.Worksheets("info for run").Activate
        infoSheet.Cells(x, y).Formula = "=HLOOKUP(B1, 'Ranks (Standard Form)'!A1:AH283," & x & " , FALSE)"
    Next y
Next x

End Sub

答案 1 :(得分:0)

您无需遍历行。 Excel允许您一次性在列中的所有单元格中输入公式。

参见我快速写的这个例子。 (的未测试

Sub Sample()
    Dim y As Long
    Dim wsInfo As Worksheet, wsRank As Worksheet
    Dim col As String, sFormula As String

    On Error GoTo Whoa

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set wsInfo = ThisWorkbook.Sheets("info for run")
    Set wsRank = ThisWorkbook.Sheets("Ranks (Standard Form)")

    '~~> Loop only through columns
    For y = 2 To 500
        '~~> Get column Name
        col = ReturnName(y)
        '~~> Store the formula in a string. Also notice the use of "$"
        '~~> If you do not want to keep the range constant then remove the "$"
        '~~> Ex: =HLOOKUP(B1,'Ranks (Standard Form)'!$A$1:$AH$283,2,FALSE)
        sFormula = "=HLOOKUP(B1,'" & wsRank.Name & "'!$A$1:$AH$283,ROW(),FALSE)"
        '~~> Insert formula in the entire column in ONE GO
        wsInfo.Range(col & "2:" & col & "152").Formula = sFormula
    Next y

LetsContinue:
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    MsgBox "Done"
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

'~~> Function to get Column Name from Column Number
Function ReturnName(ByVal num As Integer) As String
    ReturnName = Split(Cells(, num).Address, "$")(1)
End Function