首页 > 解决方案 > 将 If 语句从单个单元格复制到列中的所有单元格

问题描述

我已经能够使用以下代码使用 If/Else 语句将“打印文档”或“电子交付”输入到单元格 K2 中。我希望尝试为所有 K 列扩展相同的语句(即 K3 搜索 O3 并返回正确的值)。任何帮助将非常感激。非常感谢,迈克尔

Sub InsertType()

Dim score As Integer, result As String
score = Range("O2").Value

If score > 0 Then
    result = "Print Documents"
Else
    result = "E-Delivery"
End If

Range("K2").Value = result

End Sub

标签: excelvba

解决方案


您可以循环您的 VBA 代码:)

代码:

Sub InsertType()

Dim ws As Worksheet
Dim score As Integer, result As String
Dim i As Long
Dim lRow As Long

Set ws = ActiveWorkbook.Worksheets("Sheet1") 'Name of worksheet

lRow = ws.Cells(Rows.Count, "O").End(xlUp).Row 'Find the last row in column O



For i = 1 To lRow 'Loop from row 1 to last row
score = ws.Range(ws.Cells(i, "O"), ws.Cells(i, "O")).Value 'Take value from row i and column O

If score > 0 Then
    result = "Print Documents"
Else
    result = "E-Delivery"
End If

ws.Range(ws.Cells(i, "K"), ws.Cells(i, "K")).Value = result 'Print Result in Row i and column K
Next i

End Sub

结果:

在此处输入图像描述


推荐阅读