如题所述
Sub test()
If Application.WorksheetFunction.CountIf(Range("A1:A100"), 100) > 0 Then
MsgBox "区域A1:A100中存在100"
End If
End Sub
On Error Resume Next
Dim fn As String, matchedRow As Long
fn = "book2.xls"
If Workbooks(fn) Is Nothing Then '判断book2.xls是否打开,没有打开,则打开
Err.Clear
Workbooks.Open ThisWorkbook.Path & "\" & fn
If Err Then
MsgBox "打开“" & fn & "”失败!" & vbCrLf & "[" & Err.Number & "]" & Err.Description
Exit Sub
End If
End If
matchedRow = Application.WorksheetFunction.Match(Target.Cells(1, 1).Value, Workbooks(fn).Sheets(1).Range("A:A"), 0) '在book2.xls的sheet1的A列中查找输入的值
If Err Then '没有找到
matchedRow = Workbooks(fn).Sheets(1).Range("A65536").End(xlUp).Row + 1
Workbooks(fn).Sheets(1).Cells(matchedRow, 1) = Target.Cells(1, 1)
Workbooks(fn).Sheets(1).Cells(matchedRow, 3) = Application.WorksheetFunction.Text(Now, "yyyy/mm/dd")
Else '找到,则修改C列的值
Workbooks(fn).Sheets(1).Cells(matchedRow, 3) = Application.WorksheetFunction.Text(Now, "yyyy/mm/dd")
End If
End Sub
If Application.WorksheetFunction.CountIf(Range("A1:A100"), 100) > 0 Then
MsgBox "区域A1:A100中存在100"
End If
End Sub
使用工作表函数CountIf来统计区域中值的个数,如果大于零则存在。
示例代码中,是判断区域A1:A100中,是不是存在100
追问恩,多谢了,这样类似的,我直接用Excel里面的条件格式就满足了我的需求的,在book1.xls里面输入一个值,如何在同名文件夹下的book2.xls里面的名为"sheet1"的工作表中的A列找到相应的值,并将当前日期填入找到对应值得单元格向右移动二个(C列);如果没有找到相应的值则将book1中输入的值保存到book2.xls中的A列并将当前日期的值填入C列。这个用vba怎么实现呢?
追答Private Sub Worksheet_Change(ByVal Target As Range)On Error Resume Next
Dim fn As String, matchedRow As Long
fn = "book2.xls"
If Workbooks(fn) Is Nothing Then '判断book2.xls是否打开,没有打开,则打开
Err.Clear
Workbooks.Open ThisWorkbook.Path & "\" & fn
If Err Then
MsgBox "打开“" & fn & "”失败!" & vbCrLf & "[" & Err.Number & "]" & Err.Description
Exit Sub
End If
End If
matchedRow = Application.WorksheetFunction.Match(Target.Cells(1, 1).Value, Workbooks(fn).Sheets(1).Range("A:A"), 0) '在book2.xls的sheet1的A列中查找输入的值
If Err Then '没有找到
matchedRow = Workbooks(fn).Sheets(1).Range("A65536").End(xlUp).Row + 1
Workbooks(fn).Sheets(1).Cells(matchedRow, 1) = Target.Cells(1, 1)
Workbooks(fn).Sheets(1).Cells(matchedRow, 3) = Application.WorksheetFunction.Text(Now, "yyyy/mm/dd")
Else '找到,则修改C列的值
Workbooks(fn).Sheets(1).Cells(matchedRow, 3) = Application.WorksheetFunction.Text(Now, "yyyy/mm/dd")
End If
End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答 2014-04-14
application.countif(查找区域range,"查找内容"),返回0就是不存在,大于0就是存在追问
恩,多谢了,这样类似的,我直接用Excel里面的条件格式就满足了我的需求的,在book1.xls里面输入一个值,如何在同名文件夹下的book2.xls里面的名为"sheet1"的工作表中的A列找到相应的值,并将当前日期填入找到对应值得单元格向右移动二个(C列);如果没有找到相应的值则将book1中输入的值保存到book2.xls中的A列并将当前日期的值填入C列。这个用vba怎么实现呢?
第2个回答 2020-05-03
1、此问题可以用vba功能实现。
2、假如要判断当前选中区域内单元格是否为空,如为空则填入数字100,可以执行如下代码。
2、假如要判断当前选中区域内单元格是否为空,如为空则填入数字100,可以执行如下代码。