在查看网络上的各种来源之后,我拼凑了一个excel脚本,用于每次用户更新单元格时记录日志(注释)。它基本上创建了一个运行的更改列表,没有重复,用于跟踪项目/等的更新。下面是脚本。它最初运作良好,但突然它开始给我关于下一行Set rng1 = Range(Sheet3.Cells(rng2.Row, 2), Sheet3.Cells(rng2.Row, 2).End(xlDown)).Find(strSearch, , xlValues, xlWhole)
的类型不匹配的运行错误'13'消息,我无法弄清楚为什么它突然失败。我是VBA的新手,所以请帮助。
Sub UpdateNotes()
Dim lngLastRow As Integer
Dim n As Integer
Dim i As Integer
Dim newRow As Integer
Dim nextRow As Integer
Dim lngLastRow1 As Long
Dim strSearch As String
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
lngLastRow = Sheet1.Cells(Rows.Count, "B").End(xlUp).Row
n = lngLastRow
For i = 2 To n
strSearch = Sheet1.Cells(i, 10).Value
strSearch1 = Sheet1.Cells(i, 3).Value
Set rng2 = Sheet3.Range("A:A").Find(strSearch1, , xlValues, xlWhole)
If Not rng2 Is Nothing Then
Set rng1 = Range(Sheet3.Cells(rng2.Row, 2), Sheet3.Cells(rng2.Row, 2).End(xlDown)).Find(strSearch, , xlValues, xlWhole)
Set rng3 = Range(Sheet3.Cells(rng2.Row, [2]), Sheet3.Cells(rng2.Row, [2]).End(xlDown))
nextRow = rng3.Rows.Count + rng2.Row
Sheet3.Cells(nextRow, 1).EntireRow.Insert
Sheet3.Cells(nextRow, [2]).Value = Sheet1.Cells([i], [10]).Value
Sheet3.Cells(nextRow, 1).Value = Date
Sheet3.Cells(nextRow, 1).Font.Bold = False
Sheet3.Cells(nextRow, [2]).Font.Bold = False
End If
Else
MsgBox "Not working..." & strSearch1
End If
Next i
End Sub
ETA:经过一些调试后,如果我删除多个更新笔记的同时实例(也就是说,在没有运行更新脚本的情况下似乎同时更改的各个行),则会出现错误消失。我不确定为什么会导致此错误,但是当我删除多个未处理的更新并逐个重新输入时,程序按预期工作。关于根本原因的想法让我可以轻松避免这种情况发生?
答案 0 :(得分:0)
对于您的范围,我建议使用“with”,明确告诉Range使用哪个工作表:
Sub UpdateNotes()
Dim lngLastRow As Integer
Dim n As Integer
Dim i As Integer
Dim newRow As Integer
Dim nextRow As Integer
Dim lngLastRow1 As Long, strSearch As String, strSearch1 As String
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim sht1 As Worksheet
Dim sht3 As Worksheet
Set sht1 = Sheets("Sheet1")
Set sht3 = Sheets("Sheet3")
lngLastRow = Sheet1.Cells(Rows.Count, "B").End(xlUp).Row
n = lngLastRow
For i = 2 To n
With sht1
strSearch = .Cells(i, 10).Value
strSearch1 = .Cells(i, 3).Value
End With
With sht3
Set rng2 = .Range("A:A").Find(strSearch1, LookIn:=xlValues, lookat:=xlWhole)
If Not rng2 Is Nothing Then
Set rng1 = .Range(.Cells(rng2.Row, 2), .Cells(rng2.Row, 2).End(xlDown)).Find(strSearch, , xlValues, xlWhole)
Set rng3 = .Range(.Cells(rng2.Row, [2]), .Cells(rng2.Row, [2]).End(xlDown))
nextRow = rng3.Rows.Count + rng2.Row
.Cells(nextRow, 1).EntireRow.Insert
.Cells(nextRow, [2]).Value = sht1.Cells([i], [10]).Value
.Cells(nextRow, 1).Value = Date
.Cells(nextRow, 1).Font.Bold = False
.Cells(nextRow, [2]).Font.Bold = False
Else
MsgBox "Not working..." & strSearch1
End If
End With
Next i
End Sub
或者,更直接地,将您的范围更改为Sheet3.Range(Sheet3.Cells(rng2.Row, [2]), Sheet3.Cells(rng2.Row, [2]).End(xlDown))
。
这有什么用吗?或者仍然抛出错误?
编辑:AFAIK,你没有定义“Sheet1”,而VBA(我相信)没有内置的“Sheet1”。你可以使用Sheets(“Sheet1”)或Sheets(1)使用指数。我已将工作表设置为变量(根据需要更改其名称),并使用它来定义范围。现在应该没事。