VBA - 除列中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26997407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:17:38  来源:igfitidea点击:

VBA - divide value in column

vbadivide

提问by mglisty

as I am a complete newb in VBA, I have a question.

因为我是 VBA 的新手,所以我有一个问题。

I have a column of integers, which I want to divide by 60. The column is "X". Here's my code:

我有一列整数,我想除以 60。该列是“X”。这是我的代码:

For Each element In Worksheets("parsed").Range("X1:X" & MaxRows).Cells
    element.Value = element.Value / 60
Next

But I always get "type mismatch". What I am doing wrong?

但我总是得到“类型不匹配”。我做错了什么?

回答by Gareth

First, make sure that you declare elementas a range. Second, remove the .cellsfrom your loop. This then effectively says in your loop statement For each cell in the rangelike so:

首先,确保您声明element为一个范围。其次,.cells从循环中删除。然后,这在您的循环语句中有效地说,For each cell in the range如下所示:

Sub SomeProc()

Dim element As Range
Dim MaxRows As Long

With Worksheets("parsed")
    MaxRows = .Cells(.Rows.Count, "X").End(xlUp).Row
End With

For Each element In Worksheets("parsed").Range("X1:X" & MaxRows)
    If IsNumeric(element.Value) Then
        element.Value = element.Value / 60
    End If
Next

End Sub

I've made the assumption that MaxRowsis intended as the last row in column Xof the worksheet.

我已经假设MaxRows作为X工作表列中的最后一行。

回答by Chrismas007

Dim CurRow As Long
For CurRow = 1 to MaxRows
    element = Worksheets("parsed").Range("X" & CurRow).Value / 60
    'Do something with element for example Range(Destination).Value = element
Next CurRow