Excel中的VBA在Windows 2007计算机中运行良好,但不适用于Windows 10

时间:2017-08-02 13:15:41

标签: excel windows excel-vba vba

我有点这个VBA

Sub populateChartData()
Dim i As Integer
Dim j As Integer
Dim finalRowSheet2 As Integer
Dim k As Integer
Dim n As Integer
Dim Sheet2 As Worksheet
Dim price As Double
Dim cnt As Integer

With Worksheets("Data")
Set Sheet2 = Worksheets("Sheet2")
finalRowSheet2 = Sheet2.UsedRange.Rows.Count
For i = 2 To 5
    For j = 2 To 5
        price = 0
        cnt = 0
        For k = 2 To finalRowSheet2
            Sheet2.Cells(i, 5) = "'" & Sheet2.Cells(i, 5)
            If .Cells(i, 1) = CInt(Right(Sheet2.Cells(k, 5), 4)) And _
               .Cells(1, j) = Sheet2.Cells(k, 4) Then
                   price = price + Sheet2.Cells(k, 3) 'Col 7 if weighting is used
                   cnt = cnt + 1
            End If
        Next k
        If cnt = 0 Then
            .Cells(i, j) = 0
        Else
            .Cells(i, j) = price / cnt
        End If
    Next j

Next i
End With
End Sub

以下是数据样本

address1    3.19 mi $1,250  studio  5/1/2017
address2    3.38 mi $950    studio  7/1/2017
address3    3.48 mi $725    studio  3/1/2017
address4    3.51 mi $850    studio  7/1/2017

它在Windows 2007计算机上按预期工作。但是,当在Windows 10计算机上使用时,它会在此行上生成Type Mismatch错误

If .Cells(i, 1) = CInt(Right(Sheet2.Cells(k, 5), 4)) And _
           .Cells(1, j) = Sheet2.Cells(k, 4) Then

我已尝试进入Control Panel >> Clock, Language and Region >> Region and Language将语言设置为英语,但已将其设置为英语。我读过这可能是问题所在。我也试图尝试更改变量的类型,但到目前为止,错误继续在Windows 10机器上抛出。我希望此代码可以在两个Windows操作系统上运行而不会出现此错误。

1 个答案:

答案 0 :(得分:0)

在两个版本中运行此代码:

Public Sub TestMe()
    Debug.Print "Decimal -> "; Application.DecimalSeparator
    Debug.Print "Thausand -> "; Application.ThousandsSeparator
End Sub

如果结果不同,您就知道该怎么做了。你可以在这里阅读更多关于这个技巧的内容:

https://msdn.microsoft.com/en-us/library/office/aa215774(v=office.11).aspx