[英]VBA - If a cell in column A is not blank the column B equals
I'm looking for some code that will look at Column A and as long as the cell in Column A is not blank, then the corresponding cell in Column B will equal a specific value. 我正在寻找一些将查看列A的代码,只要列A中的单元格不为空,那么列B中的相应单元格将等于一个特定值。
So if Cell A1 <> "" then Cell B1.Value = "MyText" And repeat until a cell in Column A is blank or empty. 因此,如果单元格A1 <>“”,则单元格B1.Value =“ MyText”并重复直到列A中的单元格为空白或为空。
To add a little more clarification, I have looked through the various loop questions asked and answered here. 为了进一步说明,我浏览了这里提出和回答的各种循环问题。 They were somewhat helpful.
他们有所帮助。 However, I'm unclear on how to get the loop to go through Column A to verify that each cell in Column A isn't blank AND in the corresponding cell in Column B, add some text that I specify.
但是,我不清楚如何使循环通过A列以验证A列中的每个单元格都不为空白,并在B列中的相应单元格中添加我指定的一些文本。
Also, this will need to be part of a VBA macro and not part of a cell formula such as =IF 同样,这将需要成为VBA宏的一部分,而不是像= IF这样的单元格公式的一部分
If you really want a vba solution you can loop through a range like this: 如果您真的想要VBA解决方案,则可以遍历以下范围:
Sub Check()
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("A1:A100")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) <> "" Then
rng(i, 2).Value = "My Text"
End If
Next
End Sub
* EDIT * * 编辑 *
Instead of using varients you can just loop through the range like this: 除了使用变体,您还可以像这样遍历整个范围:
Sub Check()
Dim rng As Range
Dim i As Long
'Set the range in column A you want to loop through
Set rng = Range("A1:A100")
For Each cell In rng
'test if cell is empty
If cell.Value <> "" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "My Text"
End If
Next
End Sub
Another way (Using Formulas in VBA). 另一种方法(在VBA中使用公式)。 I guess this is the shortest VBA code as well?
我想这也是最短的VBA代码吗?
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
.Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
End With
End Sub
A simpler way to do this would be: 一种更简单的方法是:
Sub populateB()
For Each Cel in Range("A1:A100")
If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next
End Sub
使用功能IF:
=IF ( logical_test, value_if_true, value_if_false )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.