用户输入范围设置的颜色,值,粗体:运行时错误'1004':应用程序定义-对象定义错误

时间:2019-04-12 16:51:25

标签: excel vba

尝试设置用户输入范围的值,粗体和颜色

Sub Q3()
  Dim Rng As Range
  Set Rng = Application.InputBox("Range:", Type:=8)
  Set ActiveSheet.Range(Rng).Select.Value = "test"
  Range(Rng).Select.Bold = True
  Range(Rng).Select.Font.Color = -16776961
End Sub

错误1004应用程序定义-对象定义错误
另一个尝试的代码:

Sub Q3()
  Dim Rng As Range
    Set Rng = Application.InputBox("Range:", Type:=8)
    Set ActiveSheet.Range(Rng).Select.Value = "test"
    Range(Rng).Select.Bold = True
    Range(Rng).Select.Font.Color = -16776961
End Sub

错误1004对象'_Global'的方法'Range'失败

2 个答案:

答案 0 :(得分:3)

您的语法已关闭。 Rng已经是一个范围,因此无需将其包装在“范围”(或“选择”)中。

您可能要先检查输入框是否返回了某些内容。

Sub Q3()

  Dim Rng As Range

  Set Rng = Application.InputBox("Range:", Type:=8)
  With Rng
    .Value = "test"
    .Font.Bold = True
    .Font.Color = -16776961
  End With

End Sub

答案 1 :(得分:0)

除了@SJR的答案外,如果用户按下 Cancel 按钮,还需要使用错误处理来捕获情况。否则,您会遇到错误,因为InputBox返回的布尔值False不能Set到对象变量。

Option Explicit

Public Sub ProcedureQ3()
   Dim Rng As Range
   On Error Resume Next 'next line throws error if user presses cancel
   Set Rng = Application.InputBox("Range:", Type:=8)
   On Error Goto 0 're-activate error reporting

   If Rng Is Nothing Then Exit Sub 'exit if user pressed cancel

   With Rng
       .Value = "test"
       .Font.Bold = True
       .Font.Color = -16776961
   End With
End Sub