运行时错误“1004”在Excel中使用工作表vba

问题描述:

Excel正在抛出错误1004.我做错了什么?运行时错误“1004”在Excel中使用工作表vba

Private Sub CommandButton2_Click() 
    Dim x As Variant 
    x = Worksheets("Details").Range("A1").End(xlDown) 
    If OptionButton65 = True Then Worksheets("Details").Cells(x, 6) = "5" 
End Sub 

这是一个非常不好的问题,但我想这个问题是你不指定一个数字X,但单元格的值不是整数。如果你改变它如下,它可能工作。

x = Worksheets("Details").Range("A1").End(xlDown).row 
+0

您的断言是increcrec吨。 'x = Worksheets(“Details”)。Range(“A1”).End(xlDown)'隐式调用'Range'对象的默认成员,它是'_Default',它将*返回*值*细胞。 – ThunderFrame

+0

编辑。谢谢。 –

首先,因为你试图让行号,是一个Long类型变量x,而不是Variant

其次,这取决于你想在A列什么类型的最后一排找到:

选项1:发现最后一排中间无跳过空白单元格。

选项2:找到最后一行跳过中间的空白单元格。

这两个选项都在我的代码中实现,使用你想要的选项。

代码

Private Sub CommandButton2_Click() 

    Dim x As Long 

    With Worksheets("Details") 
     ' option 1 : will get you the last row with data in Column A (without skipping blank cells in the middle) 
     x = .Range("A1").End(xlDown).Row 

     ' option 2 : will get you the last row with data in Column A (with skipping blank cells in the middle) 
     x = .Cells(.Rows.Count, "A").End(xlUp).Row 

     If OptionButton65 = True Then .Cells(x, 6) = "5" 
    End With 

End Sub 

就包括实现这一点的另一种方式 - 你可以有也用Range,而不是它的财产

Private Sub CommandButton2_Click() 
    Dim x As Range 
    Set x = Worksheets("Details").Range("F1").End(xlDown) 
    If OptionButton65 = True Then x.Value = "5" 
End Sub 

或者干脆:

Private Sub CommandButton2_Click()  
    If OptionButton65 = True Then Worksheets("Details").Range("F1").End(xlDown).Value = "5" 
End Sub