识别单元格的内容,并通过Excel宏

时间:2019-01-17 20:26:12

标签: excel vba

我试图创建一个vba代码,该代码可以帮助我识别Range("A1:A5")是否具有任何数字值,如果它标识内容具有数字,请复制Range("D10")并粘贴相同的值在每个Range(B1:B5")

由于我是vba的新手,所以我开发的代码无法正常工作。

我该如何解决以下问题?

Sub Findvalues()

 Dim rng As Range, Cell As Range

 Set rng = Range("A1:A3")            'Cells data content'
 For Each Cell In rng

 If Cell.Value = "@" Then           'To identify whether cell has a number'
 Range("A10").Select                'copy ("A10") value
 Selection.Copy  

 Range("B1:B5").Select       'This is the line needs to be corrected'
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End If
Next Cell
End Sub

2 个答案:

答案 0 :(得分:3)

如果要测试Cell.Value中的数字,请尝试IsNumeric()。您还可以更改Select-Copy的方法以让Range("B1:B5") = Range("A10")生效,因为您只是在复制值。

Sub Findvalues()

Dim rng As Range, Cell As Range

Set rng = Range("A1:A3")
For Each Cell In rng
    If IsNumeric(Cell.Value) Then
        Range("B1:B5") = Range("A10")
    End If
Next Cell
End Sub

为了容纳您的评论,

Sub Findvalues()

Dim rng As Range, Cell As Range

Set rng = Range("A1:A5")
For Each Cell In rng
    If IsNumeric(Cell.Value) Then
        Cell.Offset(0,1) = Range("A10")
    End If
Next Cell
End Sub

答案 1 :(得分:1)

如果A有一个数字,它将用A10中的内容填充B:

Sub Findvalues()
    With Worksheets("Sheet7") 'change to your sheet
        Dim rng As Range
        Set rng = .Range("A1:A5")            'Cells data content'
        .Range("B1:B5") = .Evaluate("IF(ISNUMBER(" & rng.Address & "),A10,"""")")
    End With
End Sub