【发布时间】:2013-12-09 05:09:04
【问题描述】:
这是我第一次用 VBA 编写代码。 我在一个文件中有几个工作表,它们按日期排列。 所以我想做的是在工作表中收集数据集,如果它们有相同的时间段。
日期1值1
日期 2 值 2
日期3值3
由于它们是有序的,我只比较第一个日期值,如果它们不同,则转到下一个工作表。如果它们相同,则复制该值并执行相同的过程,直到到达最后一个工作表。 但是它可以很好地复制一个工作表,但之后 Excel 会冻结。
如果您发现任何错误或给我其他建议,我们将不胜感激。
以下是我的代码:
Sub matchingStock()
Dim sh1 As Worksheet, sh2 As Worksheet
' create short references to sheets
' inside the Sheets() use either the tab number or name
Set sh1 = Sheets("combined")
Dim col As Long
'since first column is for Tbill it stock price should place from the third column
col = 3
Dim k As Long
'go through all the stock worksheets
For k = Sheets("WLT").Index To Sheets("ARNA").Index
Set sh2 = Sheets(k)
' Create iterators
Dim i As Long, j As Long
' Create last rows values for the columns you will be comparing
Dim lr1 As Long, lr2 As Long
' create a reference variable to the next available row
Dim nxtRow As Long
' Create ranges to easily reference data
Dim rng1 As Range, rng2 As Range
' Assign values to variables
lr1 = sh1.Range("A" & Rows.Count).End(xlUp).Row
lr2 = sh2.Range("A" & Rows.Count).End(xlUp).Row
If sh1.Range("A3").Value = sh2.Range("A3").Value Then
Application.ScreenUpdating = False
' Loop through column A on sheet1
For i = 2 To lr1
Set rng1 = sh1.Range("A" & i)
' Loop through column A on sheet1
For j = 2 To lr2
Set rng2 = sh2.Range("A" & j)
' compare the words in column a on sheet1 with the words in column on sheet2
'Dim date1 As Date
'Dim date2 As Date
'date1 = TimeValue(sh1.Range("A3"))
'date2 = TimeValue(sh2.Range("A3"))
sh1.Cells(1, col).Value = sh2.Range("A1").Value
' find next empty row
nxtRow = sh1.Cells(Rows.Count, col).End(xlUp).Row + 1
' copy the word in column A on sheet2 to the next available row in sheet1
' copy the value ( offset(0,1) Column B ) to the next available row in sheet1
sh1.Cells(nxtRow, col).Value = rng2.Offset(0, 6).Value
'when the date is different skip to the next worksheet
Set rng2 = Nothing
Next j
Set rng1 = Nothing
Next i
'sh3.Rows("1:1").Delete
Else
GoTo Skip
End If
Skip:
col = col + 1
Next k
End Sub
【问题讨论】:
-
您是否尝试过单步执行代码以查看实际发生的情况?你在每张纸上谈论多少行?
-
正如@gtwebb 所建议的,您需要查看哪些循环是罪魁祸首,因为您的代码中有多个循环。我的猜测是 lr1 / lr2 在下一张纸上小于 2。
-
我每张纸大约有 1000 行