VBA – 范围对象只设置一次循环
我正在编写匹配date(从文件)的代码,将其放入一个集合,然后尝试在电子表格中find它。 一旦find它,它会在两个单元格的集合中放入以下两项。 当我运行这个,我得到以下错误:“对象variables或块variables未设置”。 我试图debugging我的代码,它显示在下面的代码的第一个循环后,范围对象,“rthecell”,更改为适当的值。 一旦发生循环的第二次迭代,“rthecell”的值变为“Nothing”。
例如:
Set rtheCell = Range("A:A").Find(What:=LineItem1) rtheCell.Offset(, 1).Value = LineItem3 rtheCell.Offset(, 2).Value = LineItem2 Set rtheCell = Nothing
同样,在循环的第一次迭代中,一切按预期工作,但是一旦第二次迭代发生,我就会收到错误。
以下是完整的代码:
Sub InputData() 'Declare variables Dim sFilePath As String Dim sLineFromFile As String Dim saLineItems() As String Dim element As Variant Dim col As Collection Dim LineItem1 As String Dim LineItem2 As String Dim LineItem3 As String Dim rtheCell As Range Set col = New Collection 'Insert file path name here, this file will be overwritten each morning sFilePath = "P:\Billing_Count.csv" Open sFilePath For Input As #1 Do Until EOF(1) Line Input #1, sLineFromFile 'Split each line into a string array 'First replace all space with comma, then replace all double comma with single comma 'Replace all commas with space 'Then perform split with all values separated by one space sLineFromFile = Replace(sLineFromFile, Chr(32), ",") sLineFromFile = Replace(sLineFromFile, ",,", ",") sLineFromFile = Replace(sLineFromFile, ",", " ") saLineItems = Split(sLineFromFile, " ") 'Add line from saLineItem array to a collection For Each element In saLineItems If element <> " " Then col.Add element End If Next Loop Close #1 'Place each value of array into a smaller array of size 3 Dim i As Integer i = 1 Do Until i > col.Count 'Place each value of array into a string-type variable 'This line is the date LineItem1 = col.Item(i) i = i + 1 'This line should be the BW count make sure to check LineItem2 = col.Item(i) i = i + 1 'This line should be the ECC count make sure to check LineItem3 = col.Item(i) i = i + 1 'Find the matching date in existing Daily Billing File (dates on Excel must be formatted as 'general or text) and add ECC and BW counts on adjacent fields Set rtheCell = Range("A3:A37").Find(What:=LineItem1) rtheCell.Offset(, 1).Value = LineItem3 'This is LineItem3 since we can ECC data to appear before BW rtheCell.Offset(, 2).Value = LineItem2 Set rtheCell = Nothing LineItem1 = 0 Loop 'Format cells to appear as number with no decimals 'Format cells to have horizontal alignment Sheets(1).Range("B3:C50").NumberFormat = "0" Sheets(1).Range("C3:C50").HorizontalAlignment = xlRight End Sub
当您使用Range.Find方法时 ,通常您可以在后续调用中使用After:=
参数,或者使用Range.FindNext方法 ,该方法假定After:=
上次find的项目。 由于您没有以任何方式修改实际find的单元格的值,因此您需要logging原始find的单元格(通常是地址),因为最终您将循环回到原始单元格。
dim fndrng as range, fndstr as string set fndrng = Range("A:A").Find(What:=LineItem1, after:=cells(rows.count, "A")) if not fndrng is nothing then fndstr = fndrng.address do while True 'do stuff here set fndrng = Range("A:A").FindNext(after:=fndrng) if fndstr = fndrng.address then exit do loop end if
这应该给你循环所有的匹配调用,直到你回到原来的想法。 tbh,很难充分扩大所提供的less量代码。