[英]VBA code to clear contents of cell A and B if cells C blank when macro runs from another sheet
非 VBA 方式
您可以将公式=IF(LEN(TRIM(C2))=0,"",POPULATETHISCELL)
放在单元格A
和B
,您可以在其中用您想要到达的任何内容替换POPULATETHISCELL 。 例如,填充今天的日期。
VBA方式
Objects
。 避免使用ActiveWorkbook/Activesheet/Selection
等作为展示HEREUsedRange
。 查找如图最后一排的位置,然后通过它循环。这是你正在尝试的吗?
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lastrow As Long
Dim i As Long
Set ws = ThisWorkbook.Sheets("Sold")
With ws
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
For i = 2 To lastrow
If Len(Trim(.Range("C" & i).Value)) = 0 Then _
.Range("A" & i & ":B" & i).ClearContents
Next i
End If
End With
End Sub
您需要包含工作表的名称。
Sub Clear()
Dim g As Long
With ActiveWorkbook.Sheets("Sold")
For g = 2 To .UsedRange.Rows.Count
If .Cells(g, "C").Value = "" Then
.Cells(g, "A").ClearContents
.Cells(g, "B").ClearContents
End If
Next
End With
End Sub
尝试类似:
Sub Sample()
'============ Init ================
Dim Ws_Sold As Worksheet
Set Ws_Sold = Sheets("Sold")
Dim count As Integer
count = 1
Dim lastrow As Long
lastrow = Ws_Sold.Cells.SpecialCells(xlCellTypeLastCell).Row
'give number of the last cell not empty
'============ loop================
While (count < lastrow + 1)
If Ws_Sold.Cells(count, 3).Value = "" Then
Ws_Sold.Cells(count, 1).ClearContents
Ws_Sold.Cells(count, 2).ClearContents
End If
count = count + 1
Wend
结束子
祝你今天过得愉快 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.