excel - Excel Object Required Error when Running Macro
问题描述
I am trying to create a macro such that if a given cell in the range L2:L318 contains a particular value, the cell in column H in the same row is modified to a new string.
At this point, I have what appears to be something passable, but I get an 'Object Required' error when it runs. My code is as follows:
Sub Macro2()
Dim rng As Range
Dim cell As Range
Set rng = Worksheet.Range("L2:L318")
Dim i As Integer
For Each cell In rng
If cell.Value("902.4") Then
i = i + 1
Sheet.Cells(8, i).Value = "Text"
Else
i = i + 1
End If
Next cell
End Sub
I'll admit I haven't the slightest idea what I'm doing, and there's at least a moderate chance my code is complete nonsense. Can anyone explain to me what I'm doing wrong? Any help would be appreciated - I've literally never touched Excel macros before today!
解决方案
This is a great start! You've got a few things off, but for the most part you weren't too far off. Keep in mind there are a ton of different ways to approach this, but since you're learning, I took your approach and made it work. See if this gets you close to what you're after:
Sub Macro2()
Dim rng As Range
Dim cell As Range
Set rng = Range("L2:L318")
For Each cell In rng
If cell.Value = 902.4 Then Cells(cell.Row, 8).Value = "Text"
Next cell
End Sub
Take a look at what I posted and see if you can make heads or tails of it. As you can see, it's not too far off what you had, just cleaned up a little and fixed the syntax.
Keep in mind, this macro will run on the currently active sheet. If you need it to run on a specific sheet, you'll have to qualify your range reference a bit better...something like: Worksheets("your worksheet name").Range("L2:L318")
推荐阅读
- vb.net - 如何设置最多两个numericupdown控件
- android - 如何防止一个活动的 addValueEventListener 在另一个活动中被调用?
- jquery - 如何触发 orl 事件
- c++ - 试图了解可以通过 SetProcessMitigationPolicy 函数设置的流程缓解策略
- javascript - 如何使用 JavaScript 放大图像?
- python - 具有定义截距的线性回归
- react-native - Undefined 不是 _reactNavigation.StackNavigator 附近的函数
- python - 返回属性名称 Networkx Python
- php - 无法在 PHP 中循环遍历数组
- github - ssh正常时如何修复github权限被拒绝