Excel VBA函数检查文件名是否包含值
我需要一个公式,会输出这样的东西:
如果特定文件夹中的文件名包含(因为文件名将在@字符后有一个附加string),所以如果文件名包含单元格值AB1,则在单元格AC1中添加完整文件名。
用VBA可以吗?
非常感谢
这在VBA中可行吗?
当然。 下面是我一直使用的VBA辅助函数:
Public Function Contains(ByVal string_source As String, ByVal find_text As String, Optional ByVal caseSensitive As Boolean = False) As Boolean Dim compareMethod As VbCompareMethod If caseSensitive Then compareMethod = vbBinaryCompare Else compareMethod = vbTextCompare End If Contains = (InStr(1, string_source, find_text, compareMethod) <> 0) End Function
我也使用这一个,当我有多个值检查 – 它比performance好比If {check1} Or {check2} Or {check3}...
因为它返回一find匹配,所以{check42}
如果{check1}
返回,则不会被评估为True
:
Public Function ContainsAny(ByVal string_source As String, ByVal caseSensitive As Boolean, ParamArray find_strings() As Variant) As Boolean Dim find As String, i As Integer, found As Boolean For i = LBound(find_strings) To UBound(find_strings) find = CStr(find_strings(i)) found = Contains(string_source, find, caseSensitive) If found Then Exit For Next ContainsAny = found End Function
考虑:
Sub qwerty() Dim FileSpec As String, FileName As String Dim v As String FileSpec = "C:\TestFolder\2013\Fed taxes\qwerty31416.xlsm" ary = Split(FileSpec, "\") FileName = ary(UBound(ary)) v = Range("AB1").Value If InStr(1, FileName, v) > 0 Then Range("AC1").Value = FileName End If End Sub