简体   繁体   English

将单元格值添加到整数(Excel-VBA)

[英]Adding Cell Value to an Integer (Excel-VBA)

With years of programming experience (beginner with VBA, however), online references, and search engines I'm yet frustrated to the utmost with my inability to get this to work. 凭借多年的编程经验(无论是VBA的初学者),在线参考和搜索引擎,我还是因为无法实现这一目标而受挫。

I've spent at least two hours trying every combination of CInt, .Range, With/End With, .Value, Cells, etc. that I could possibly think of and it just keeps failing on the "sum = sum + ..." line: 我花了至少两个小时尝试CInt,.Range,With / End With,.Value,Cells等的每一个组合,我可能会想到它,它只是在“sum = sum + ... “行:

Public Sub Fill_InnerData()

    Dim GNumber As Range
    Set GNumber = Range("GenerateNumber")

    Dim Data As Range
    Set Data = Range("DATA_INNER")

    For r = 1 To Data.Rows.Count

        For c = 1 To Data.Columns.Count

            If Data.Cells(r, c) = "" Then

                If c > r Then

                    Data.Cells(r, c) = 0

                Else
                    Dim x As Integer
                    x = r - c + 1

                    Dim y As Integer
                    y = 2

                    Dim sum As Integer
                    sum = 1

                    For i = 1 To c
                        sum = sum + CInt(Worksheets("Data").Range(Cells(x, y)).Value)
                        y = y + 1
                    Next

                End If

            End If

        Next
    Next

End Sub

By "failing" I mean getting this error: 通过“失败”我的意思是得到这个错误:

Run-time error '1004': 运行时错误'1004':

Application-defined or object-defined error 应用程序定义或对象定义的错误

I've received that error at the mentioned line with EVERY combination that I tried. 我在上面提到的那条线路上收到了这个错误。

What am I doing wrong? 我究竟做错了什么?

The think here is with your syntax referring to range. 这里的思考是你的语法指的是范围。 It should be enough to cut it a bit and do it this way: 它应该足够削减一点,这样做:

Sum = Sum + CInt(Worksheets("Data").Cells(x, y).Value)

According to my experiences range requires address string inside parenthesis if only one argument is provided. 根据我的经验,如果只提供一个参数,则范围内需要括号内的地址字符串。 Or you can put Cells if you provide both starting and ending range points. 或者,如果同时提供起始和结束范围点,则可以放置单元格。 This two simple lines has correct syntax: 这两个简单的行具有正确的语法:

Range(Cells(1,1), Cells(2,2)).Select
Range(Cells(1,1).Address).Select

This is not valid: 这是无效的:

Range(Cells(1,1)).Select    'error 1004 here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM