Excel 将IF函数与文本一起使用
我正在尝试制作一个VBA宏,它将在D列中查找特定值,并将文本输入到其他3个列中。我相信我很快就能得到我需要的答案,但我不确定我错过了什么才能让它发挥作用 以下是我目前掌握的情况:Excel 将IF函数与文本一起使用,excel,vba,Excel,Vba,我正在尝试制作一个VBA宏,它将在D列中查找特定值,并将文本输入到其他3个列中。我相信我很快就能得到我需要的答案,但我不确定我错过了什么才能让它发挥作用 以下是我目前掌握的情况: Dim rng As range Dim i As Long 'Set the range in column D you want to loop through **Set rng = range("D3:D")** For Each cell In rng 'Test cell for CR I
Dim rng As range
Dim i As Long
'Set the range in column D you want to loop through
**Set rng = range("D3:D")**
For Each cell In rng
'Test cell for CR
If cell.Value = "CR" Then
'write to adjacent cell
cell.Offset(0, 3).Value = "CREDIT"
cell.Offset(0, 5).Value = "CREDIT"
cell.Offset(0, 6).Value = "CREDIT"
End If
Next
**Set rng = range("G3:G")**
For Each cell In rng
'test for empty cell
If cell.Value = "" Then
'write to adjacent cell
cell.Offset(0, 0).Value = "FREIGHT"
cell.Offset(0, 2).Value = "FREIGHT"
cell.Offset(0, 3).Value = "FREIGHT"
End If
Next
End Sub
带**的行是我遇到错误的地方
非常感谢您的帮助 试试这个:
Set rng = Range("D3", Cells(Rows.Count, "D").End(xlUp))
这是一种基于给定单元格及其
结束(xlDown)
声明范围的方法:
其思想是,给定工作表上的任意两个单元格都可以定义一个范围。因此,通过定义它们,范围也得到了定义
这两个单元格是
firstCell
和lastCell
。有趣的是,您只需要声明firstCell
的父对象(worksheet
),然后lastCell
和myRange
使用相同的对象。范围中的最后一个单元格是什么?不能只有起始单元格而没有结束单元格。你需要,比如说,Set rng=Range(“D3:D”和lastRow)
(其中lastRow
是说Dim lastRow,只要长//lastRow=Rance(“D”&rows.count”)。End(xlUp)。Row
),或者Set rng=Range(“D3:D100”)
。你也可以完全限定你使用的表格。除非你的代码应该是一个工作表对象。谢谢你指出这一点——我在“lastrow”中添加了它,因为这会有所不同。代码都是基于这张表的,所以我不认为我需要对它进行限定,因为我不需要附加其他代码。
Option Explicit
Sub TestMe()
Dim myRange As Range
Dim firstCell As Range
Dim lastCell As Range
Set firstCell = Worksheets(1).Range("A12")
Set lastCell = firstCell.End(xlDown)
Set myRange = Range(firstCell, lastCell)
End Sub