循环时VBA动态行查找

时间:2018-03-29 15:48:02

标签: excel-vba runtime-error vba excel

我对VBA非常陌生,应该花一些时间来调试和学习编写代码的方式。

我正在使用一个循环,该循环使用Hlookup函数从一张表上填充一张表与主表上的数据。 (这是在Sub SetMatrix中)。在执行此任务的Sub中,我使用了一些其他UDF,一个复制并粘贴变量(第三张中可能更改的名称)我想从主表中查找。

在任何情况下,当我在查找函数中使用硬编码的行时,它运行得非常好。但是,一旦我尝试使用变量(jpmRow而不是50之类的数字),它将仅在第一次工作。然后,当我再次运行它时,我得到RunTime错误91 - 未设置对象变量或withblock变量。调试器将我带回DynamicRange UDF,Set StartCell行,这让我感到困惑,因为那不是我设置行变量的地方。同时,如果我在行中使用常量,则每次都能让我重新运行sub。

以下是代码:

Option Explicit

Dim wsTemplate As Worksheet
Dim ws As Worksheet
Dim TxtCell As Range
Dim PortfolioCell As String
Dim StartCell As Range
Dim EndCell As Range
Dim RangeParameter As Range
Dim jpmRow As Integer
Dim myColumn As Integer
Dim myRow As Integer



Function DynamicRange(TxtToFind As String) As Range


Dim k As Integer

k = iCount

Set ws = Sheets("Template")

Set StartCell = ws.Cells.Find(TxtToFind).Offset(2, 0)
myColumn = StartCell.Column
myRow = StartCell.Row
Set EndCell = ws.Cells(myRow + k - 1, myColumn)

Set DynamicRange = ws.Range(StartCell.Address, EndCell.Address)

'Set DynamicRange = RangeParameter

End Function
Function iCount() As Integer



Set ws = Sheets("Template")

Set StartCell = ws.Cells.Find("Ticker").Offset(2, 0)
Set EndCell = ws.Cells.Find("Total").Offset(-1, 0)

iCount = ws.Range(StartCell.Address, EndCell.Address).Rows.Count


End Function



Sub SetMatrix()

Dim StartTable As Range
Dim iRows As Range
Dim iColumns As Range
Dim myArray(50, 50) As Integer

Dim wsJPM As Worksheet
Dim i As Integer
Dim j As Integer


Set StartTable = Sheets("Correlation Matrix").Range("A3")
Set iRows = Range(StartTable.Offset(1, 0).Address, StartTable.Offset(iCount, 0).Address)
Set iColumns = Range(StartTable.Offset(0, 1).Address, StartTable.Offset(0, iCount).Address)
Set wsJPM = Sheets("JPM")

Sheets("Correlation Matrix").Cells.ClearContents
Sheets("Correlation Matrix").Cells.ClearFormats

DynamicRange("Asset Class").Copy iRows
DynamicRange("Asset Class").Copy
iColumns.PasteSpecial Transpose:=True


For i = 1 To iCount

    For j = 1 To iCount
    jpmRow = wsJPM.Cells.Find(StartTable.Offset(i, 0), SearchOrder:=xlColumns, LookAt:=xlWhole).Row
    StartTable.Offset(i, j).Value = Application.WorksheetFunction.HLookup(StartTable.Offset(0, j), Sheets("JPM").Range("B1:BZ100"), jpmRow, False)
    Next j

Next i


End Sub

0 个答案:

没有答案