运行时错误'1004':选择范围类失败的VBA方法

时间:2016-09-25 08:47:37

标签: excel vba runtime-error

我在下面的代码上遇到运行时错误,请你协助。 部件和获取错误的是rngRange.Select。您能否以任何方式提出修改以下代码的建议?提前谢谢

Sub NameRangeTop(Optional ByRef rngRange As Range)

If rngRange Is Nothing Then
    Set rngRange = Application.Selection
Else
    rngRange.Select
End If

Dim ActiveRange As Range
Dim NumRows, NumColumns, iCount As Long

Dim CurSheetName As String
CurSheetName = ActiveSheet.Name

Set ActiveRange = Selection.CurrentRegion
ActiveRange.Select
NumRows = ActiveRange.Rows.Count
NumColumns = ActiveRange.Columns.Count

If NumRows = 1 And NumColumns = 1 Then
MsgBox "No active cells in the surrounding area. Try running the macro from a different location", vbCritical, "Local Range Naming"
Exit Sub
End If

If NumRows = 1 Then
    Set ActiveRange = ActiveRange.Resize(2)
    NumRows = 2
End If

For iCount = 1 To NumColumns
ActiveRange.Resize(NumRows - 1).Offset(1, 0).Columns(iCount).Name = CurSheetName & "!" & ActiveRange.Rows(1).Columns(iCount).Value
Next

ActiveRange.Resize(NumRows - 1).Offset(1, 0).Select

End Sub

1 个答案:

答案 0 :(得分:0)

这是因为传递的rngRange范围不属于当前活动的工作表

像这样的代码

If rngRange Is Nothing Then
    Set rngRange = Application.Selection
Else
    rngRange.Parent.Activate
    rngRange.Select
End If