将文本从UserForm文本框粘贴到另一个工作表上的ActiveCell对应的单元格

时间:2019-06-24 14:43:24

标签: excel vba

我想获取活动单元格地址,然后使用它从同一工作簿中另一张工作表上的用户窗体文本框中输入文本。我试图使它与下面的代码一起使用,但不起作用。

所以我尝试Set acad = ActiveCell.Address并在ThisWorkbook.Worksheets("Data").Range(acad).Value = "hello"中使用它

这是我的解决方法:

Private Sub CommandButton25_Click()

Dim r As Range
Dim acad As Range

On Error GoTo noval

Set r = Cells.SpecialCells(xlCellTypeAllValidation)

Set acad = ActiveCell.Address

If Intersect(r, ActiveCell) Is Nothing Then GoTo noval

ActiveCell.Validation.Delete

With ActiveCell.Validation
 .Add Type:=xlValidateInputOnly
 .InputTitle = Me.TextBox1.Value
 .InputMessage = Me.TextBox2.Value
 End With

 ThisWorkbook.Worksheets("Data").Range(acad).Value = "hello"

 ActiveCell.Offset(0, 1).Interior.ColorIndex = 4

Exit Sub

noval:

With ActiveCell.Validation
 .Add Type:=xlValidateInputOnly
 .InputTitle = Me.TextBox1.Value
 .InputMessage = Me.TextBox2.Value
 End With

 ActiveCell.Offset(0, 1).Interior.ColorIndex = 4

On Error GoTo 0

'ActiveCell.Value = ActiveCell.Value & "   " & ""

End Sub

1 个答案:

答案 0 :(得分:1)

您的分配(Set acad = ...)是从字符串到对象,这可能会给您带来424错误必需的对象,因为Address返回的是字符串,而不是Range对象。

然后您可能需要做:ThisWorkbook.Worksheets("Data").Range(acad.Address).Value = "hello"

Private Sub CommandButton25_Click()
Dim r As Range
Dim acad As Range

Set r = Cells.SpecialCells(xlCellTypeAllValidation)
Set acad = ActiveCell

With acad.Validation
    .Delete
    .Add Type:=xlValidateInputOnly
    .InputTitle = Me.TextBox1.Value
    .InputMessage = Me.TextBox2.Value
End With
acad.Offset(0, 1).Interior.ColorIndex = 4

ThisWorkbook.Worksheets("Data").Range(acad.Address).Value = "hello"

End Sub