关于clearcontent的VBA运行时错误1004

时间:2018-04-03 23:10:49

标签: vba clear

我试图让我的宏(下一个单词)从列表中选择一个随机单词,然后另一个宏(定义)执行vlookup来返回定义。当我选择宏来获取一个新单词时,我需要它来清除宏的定义,这样我才能看到它直到我选择定义按钮。现在我得到运行时错误1004,它最后突出显示我的.clearcontent代码。

enter image description here

Sub showRandomWord()
Dim ws As Worksheet, ws2 As Worksheet
Dim stRow As Long, endRow As Long, dataCol As Long
Dim dispRow As Long, dispCol As Long

Set ws = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
stRow = 2
dataCol = 1
dispRow = 2
dispCol = 2

With ws
    endRow = .Cells(.Rows.Count, dataCol).End(xlUp).Row
End With
ws2.Cells(dispRow, dispCol).Value = 
ws.Cells(Application.RandBetween(stRow, endRow), dataCol).Value

Worksheets("Sheet2").Range("J2").ClearContents

 End Sub

1 个答案:

答案 0 :(得分:1)

使用MergeArea

Sub showRandomWord()
Dim ws As Worksheet, ws2 As Worksheet
Dim stRow As Long, endRow As Long, dataCol As Long
Dim dispRow As Long, dispCol As Long

Set ws = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
stRow = 2
dataCol = 1
dispRow = 2
dispCol = 2

With ws
    endRow = .Cells(.Rows.Count, dataCol).End(xlUp).Row
End With

ws2.Cells(dispRow, dispCol).Value = ""
ws.Cells(Application.RandBetween(stRow, endRow), dataCol).Value

ws2.Range("J2").MergeArea.ClearContents

End Sub