Excel VBA - 一次循环一列

Excel VBA - Loop through column one at a time

我正在尝试遍历 Sht1 (B2:B138) 中的每一行,并为该循环中的每个项目设置一个 "input" 单元格 Sht2 (A1),一次一个。然后,"output" 单元格 Sht2 (N7) 中的值将被复制回 Sht1 (C2:C138)


例如:

Sht2 (A1) = value in Sht1 (B2), 那么 Sht1 (C2) = value in Sht2 (N7)

重复

Sht2 (A1) = value in Sht1 (B3), 那么 Sht1 (C3) = value in Sht2 (N7)


一遍又一遍,直到它到达列表的底部。最终我可能不得不扩展 Sht1 ColB 中的列表,因此我一直在尝试让它动态评估所需的迭代次数。

我在下面尝试的代码为我提供了所有正确的 "outputs",但它们并没有出现在 Sht2 ColC 中的正确单元格中。请看下面。我研究并找到了 this Q/A to be helpful and used it to influence the code. I appreciate your help in advance. My workbook 以备不时之需。

Sub fnDescCalc()
'Define the objects

Dim wb As Workbook
Dim Framework As Worksheet
Dim SumFramework As Worksheet
Dim colB As Long
Dim colC As Long
Dim LastcolC As Integer
Dim LastcolB As Long

'Set the Variables
Set wb = ThisWorkbook
Set Framework = wb.Sheets("Framework")
Set SumFramework = wb.Sheets("Sum_Framework")

LastRowcb = Framework.Range("B:B").Find("*", searchdirection:=xlPrevious).Row
colB = 2

LastcolC = 138

'This is the beginning of the main loop
For colC = 2 To LastcolC

'This is the beginning of the nested loop
    For colB = 2 To LastcolB
    SumFramework.Range("A1") = Framework.Range("B" & colB).Value
    colB = colB + 1

Framework.Range("C" & colC) = SumFramework.Range("N7").Value
colC = colC + 1

Next colB

Next colC

End Sub

您提供的说明和代码不符。所以我了解到您想执行以下操作:

您输入了 2 个值。搜索值 (SumFramework.Range("A1")) 和输入值 (SumFramework.Range("N7"))。现在 Sheet "Framework" 的 B 列列表中与搜索值匹配的每个项目都被分配了 C 列中的输入值。如果我的理解有误,请详细说明:)

1。 在您的代码中,LastcolB 永远不会被初始化,因此它将为 0,并且循环永远不会执行。

2。 您只需要一个循环即可完成 [编辑:您在评论中描述]:

MaxRow = Framework.Range("B:B").Find("*", searchdirection:=xlPrevious).Row
'Alternative if the last row is the actual last row and .Row < 1000:
'MaxRow = Framework.Range("B1000").End(xlUp).Row


For rowB = 2 To MaxRow
    SumFramework.Range("A1") = Framework.Range("B" & rowB).Value
    Framework.Range("C" & rowB) = SumFramework.Range("N7").Value
Next rowB
  1. "For...Next" 自动向上计数。使用 colB = colB + 1 可以跳过每个部分行。