想知道是否有人可以帮我解决以下问题。
我在With Worksheets("Sheet1").Cells(Rowtosave, EGCheck)
时遇到了运行时错误1004,我花了很长时间尝试但仍然无法自己定义错误。谁应该好看,小心帮我出去?非常感谢您的帮助。谢谢!
Sub Macro1()
Dim LastRow1 As Long, RowCheck As Long, Rowtosave As Long, LastCol1 As Long
Dim EGCheck As Long, ColEG As Range, firstEG As Long
LastRow1 = 50
LastCol1 = 50
For RowCheck = 1 To LastRow1
'Look for "Name"
With Worksheets("Sheet1").Cells(RowCheck, 1)
If .Value = "Name" Then
'Set row to Rowtosave for later use
Rowtosave = RowCheck
End If
End With
Next RowCheck
For EGCheck = 1 To LastCol1
'Look for EG on the name row with varying column
'Since already obtain the row for name as Rowtosave, so set Row to Rowtosave
With Worksheets("Sheet1").Cells(Rowtosave, EGCheck)
If .Value = "EG" Then
firstEG = EGCheck
End If
End With
Next EGCheck
答案 0 :(得分:1)
您的情况有问题,此处未显示。当我输入以下内容时:
Option Explicit
Sub Macro1()
Dim LastRow1 As Long, RowCheck As Long, Rowtosave As Long
Dim LastCol1 As Long, EGCheck As Long
Range("a1:a1").Value = -1
LastRow1 = 50
LastCol1 = 50
For RowCheck = 1 To LastRow1
With Worksheets("Sheet1").Cells(RowCheck, 1)
If .Value = "Name" Then
Rowtosave = RowCheck
End If
End With
Next RowCheck
For EGCheck = 1 To LastCol1
With Worksheets("Sheet1").Cells(Rowtosave, EGCheck)
If .Value = "EG" Then
Range("a1:a1").Value = Rowtosave * 10 + EGCheck
End If
End With
Next EGCheck
End Sub
并将Name
和EG
分别放入单元格A6
和D6
,最后我在单元格64
中找到了A1
,预期。换句话说,它工作正常。
但是,如果我从单元格Name
中移除 A6
,则会收到错误1004,与您相同。那是因为,在这种情况下,永远不会设置Rowtocheck
,因此它的默认值为零。
并且,当您尝试在Cells()
调用中使用0作为rown时,它会出错,因为该行必须是一行或多行。
答案 1 :(得分:0)
不知道您的样本数据是什么,很难说。但我怀疑设置“Rowtosave”的条件永远不会被满足,因此Rowtosave = 0.没有行/列0,所以当代码中的可疑行运行时(此行):
With Worksheets("Sheet1").Cells(Rowtosave, EGCheck)
,这是错误的。