我的VBA IsNumeric功能有什么问题?

时间:2015-12-03 20:56:18

标签: excel vba excel-vba excel-2016

我找不到这段代码有什么问题,每次我尝试将其更改为我认为会更好地运行的东西,它会显示为错误。非常感谢您的帮助!

这是代码,它专门用于使用isnumeric函数,我在Mac上使用Excel 2016。

Dim ws1 As Worksheet
Dim ws2 As Worksheet



Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")

Set i = 1
Set n = 1

Do While ws1.Cell(i, "F") <> "End"
Num1 = ws1.Cell(i, "F")
    If IsNumeric(Num1.value) <> False And Num1 <> ""
        Set ws2.Cell(n, "B") = ws1.Cell(i, "F")
        n = n + 1
        End If
    Next i

1 个答案:

答案 0 :(得分:3)

也许你根本不需要VBA。对于非vba解决方案,请在Sheet2单元格B1中输入此公式,并根据需要向下拖动多行(在Sheet1列F中)。

=IF(AND(NOT(ISNUMBER(Sheet1!F1)),Sheet1!F1=""),Sheet1!F1,"")

对于VBA解决方案,我为了许多关闭的语法错误清理了一些代码。另外,请注意以下事项:

  1. 始终在模块中使用Option Explicit并声明所有变量类型
  2. 始终使用变量限定对象
  3. (1和2是最佳做法,但不是必需的。将事情排除可能会产生意外结果。

    Option Explicit
    
    '... Sub Name ...
    Dim wb as Workbook
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim Num1 as Variant
    
    Set wb = ThisWorkbook 'or Workbooks("myBook")
    Set ws1 = wb.Sheets("Sheet1")
    Set ws2 = wb.Sheets("Sheet2")
    
    Dim i as Long, n as Long
    i = 1 'no need to "Set" numerical integers
    n = 1
    
    Do While ws1.Cells(i, "F") <> "End"
        Num1 = ws1.Cells(i, "F").Value2 'set this to the value2 property of the cell
        If Not IsNumeric(Num1) And Num1 <> "" 'remove .Value from variable
            ws2.Cells(n, "B").Value = ws1.Cells(i, "F").Value 'set the cells Value property equal to each ... again, Set will not work here
            n = n + 1
            i = i + 1 'need to increment i as well
        End If
    Loop 'not Next I, since you are using a Do While Loop