如何将单元格值设置为循环内容?

发布于 2024-12-17 10:04:53 字数 390 浏览 1 评论 0原文

我下面有这个代码。如何将单元格值设置为 = 循环该值的内容?

Sub Test2()
      ' Select cell A2, *first line of data*.
      Range("A2").Select
      ' Set Do loop to stop when an empty cell is reached.
      Do Until IsEmpty(ActiveCell)
         ' Insert your code here.
         ' Step down 1 row from present location.
         ActiveCell.Offset(1, 0).Select
      Loop
   End Sub

I have this code below. How can I set a cell value to = whats looping through that value?

Sub Test2()
      ' Select cell A2, *first line of data*.
      Range("A2").Select
      ' Set Do loop to stop when an empty cell is reached.
      Do Until IsEmpty(ActiveCell)
         ' Insert your code here.
         ' Step down 1 row from present location.
         ActiveCell.Offset(1, 0).Select
      Loop
   End Sub

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半城柳色半声笛 2024-12-24 10:04:53

我的答案看起来更像是评论,但它太长,无法放入评论(并且无法正确格式化)。

如何循环范围

我建议您查看 Chip Pearson 页面 了解有关优化 VBA,尤其是 VBA 中的范围循环。

当您遍历范围时,您应该使用 foreach 语句,如本示例中所述:

Dim WS as Worksheet
For Each WS In Worksheets
    MsgBox WS.Name
Next WS

Dim i as Integer
For i = 1 To Worksheets.Count
    MsgBox Worksheets(i).Name
Next i

查找最后一个空单元格

您的代码似乎尝试查找最后一个空单元格。您可以轻松地使用

With ActiveWorkbook.Worksheets("Sheet1")
    .Cells(.Rows.Count,1).End(xlUp)
End With

您可以在 ozgrid 上找到更多提示(即使它们不要使用rows.count

避免选择

如果您尝试选择循环中的每个单元格,您的代码将会非常非常慢

你最好使用VBA的对象模型
例如,如果您只想复制单元格的

不做

Range("A1").Select
Selection.Copy
Range("A2").Select
Selection.Paste

Range("A2").Value = Range("A1").Value

My answer will better look like a comment but it is too long to fit in a comment (and cannot be formatted properly).

How to loop over a range

I advise you to have a look at Chip Pearson page about optimizing VBA, especially looping over range in VBA.

When you loop over range, you shoul use the for each statement as described in this example:

Dim WS as Worksheet
For Each WS In Worksheets
    MsgBox WS.Name
Next WS

Dim i as Integer
For i = 1 To Worksheets.Count
    MsgBox Worksheets(i).Name
Next i

Finding the last empty cell

Your code seems to try to find the last empty cell. You can do it easily with

With ActiveWorkbook.Worksheets("Sheet1")
    .Cells(.Rows.Count,1).End(xlUp)
End With

You can find some more tips on ozgrid (even if they don't use rows.count)

Avoiding Selects

Your code will be very very slow if you are trying to Select every cell in a loop.

You'd better use the object model of VBA.
For instance, if you only want to copy the value of a cell:

Don't do

Range("A1").Select
Selection.Copy
Range("A2").Select
Selection.Paste

Do

Range("A2").Value = Range("A1").Value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文