2016-10-27 105 views
-1

我正在使用VBA执行一个数据透视表字段的搜索,我希望能够做一个基于字段是否包含字符串的一部分,但不确定如何做这个没有检查为整体价值。波纹管是我目前拥有的:VBA字段包含

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 

'This line stops the worksheet updating on every change, it only updates when cell 
'P4 is touched 
If Intersect(Target, Range("B4")) Is Nothing Then Exit Sub 

'Set the Variables to be used 
Dim pt As PivotTable 
Dim Field As PivotField 
Dim NewPull As String 

'Here you amend to suit your data 
Set pt = Worksheets("Pull Code Search").PivotTables("PivotTable1") 
Set Field = pt.PivotFields("Pull Code") 
If IsEmpty(Range("B3").Value) = True Then 
    NewPull = "(All)" 
Else 
    NewPull = Worksheets("Pull Code Search").Range("B3").Value 
End If 

'This updates and refreshes the PIVOT table 
With pt 
Field.ClearAllFilters 
Field.CurrentPage = NewPull 

    If NewPull = "(All)" Then 
     ActiveSheet.PivotTables(1).PivotFields(1).ShowDetail = False 
    End If 

pt.RefreshTable 
End With 

End Sub 

回答

1

使用INSTR。

该函数返回字符串中第一次出现子串的位置。你不需要遍历整个字符串。

如果您的字符串部分(子字符串)存在于实际的“字符串”中,则此函数返回正值。

的INSTR功能只能在Microsoft Excel中VBA代码中使用。”

语法

InStr([start], string, substring, [compare]) 

更多的描述在这里:

https://www.techonthenet.com/excel/formulas/instr.php

+0

FWIW'InStr函数'也有[Docs.SO专用主题](http://stackoverflow.com/documentation/vba/3480/searching-within-stri NGS-为最存在-的子串#吨= 20161027203242050143)。 –

+0

太好了。谢谢。 – Naidu

+0

无法确定在这种情况下如何使用它。 –