【问题标题】:Type mismatch in VBA, cant do operations with Cells(x,x).ValueVBA 中的类型不匹配,无法使用 Cells(x,x).Value 进行操作
【发布时间】:2016-07-11 16:50:53
【问题描述】:

所以我正在尝试编写一个宏来计算一些相对值。我基本上遍历整个列,取一些值并将其除以另一个值并写在另一列中。该程序无关紧要。困扰我的是我在 hold3=hold/hold2 中得到类型不匹配。我就这样崩溃了(使用hold、hold2、hold3)来看看问题出在哪里。它在分区中。如果我只是离开 hold3=hold 它不会给我一个错误。当我尝试除法或求和或进行任何操作时,它会给我不匹配错误。我尝试将所有变量声明为双精度,根本不使用任何变量(用于 Cells(i,8).Value = Cells(i,7).Value/Cells(cuenta,7) )并且没有任何效果。

Sub DivideByTotal()  
Dim innerTop As Long
Dim counter As Long

Dim hold As Variant
Dim hold2 As Variant
Dim hold3 As Variant


For counter = 9 To 559
    innerTop = counter + 4
    Dim i As Long
    For i = counter To innerTop
        Dim cuenta As Long
        cuenta = counter
        hold = Cells(i, 7).Value
        hold2 = Cells(cuenta, 7).Value
        hold3 = hold / hold2
        Cells(i, 8).Value = hold3
    Next i
    counter = counter + 4
Next counter
End Sub

【问题讨论】:

  • 使用 Debug.Print holdDebug.Print hold2 检查你用来做除法的值是什么。您也可以使用 msgbox holdmsgbox hold2 来实现相同的效果。
  • 如果你有一个空白单元格,你会在使用变体时得到这个错误。

标签: vba excel


【解决方案1】:

试试这个:

Sub DivideByTotal()

Dim innerTop As Long
Dim counter As Long
Dim i As Long
Dim hold As Double
Dim hold2 As Double
Dim hold3 As Double
Dim wk As Worksheet
Dim cuenta As Long    

Set wk=Sheet1   'Replace it with the sheet number

With wk
For counter = 9 To 559
    innerTop = counter + 4

    For i = counter To innerTop
        cuenta = counter
        hold = .Cells(i, 7).Value
        hold2 = .Cells(cuenta, 7).Value
        if Isnumeric(hold)=0 or isnumeric(hold2)=0 then  'Check if hold and hold2 are numbers or not.
              Debug.Print hold
              Debug.Print hold2
        ELse 
            hold3 = hold / hold2
            .Cells(i, 8).Value = hold3
        End if
    Next i
    counter = counter + 4

Next counter
End With

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多