从CSV中提取特定的多个值

时间:2019-06-02 15:46:35

标签: excel vba csv

所以我有一个包含名称位置性别和电子邮件地址的CSV文件,因此我需要对其进行过滤以仅包含美国电子邮件,是否有可能基于包含美国州或城市的原始信息来提取电子邮件?因此,例如,在位置列中有“ Ely- Nevada”,我想提取它,用一个值并不难,但是要如何处理像美国每个州和城市这样的几个值(我可以得出整数在此处列出:https://www.britannica.com/topic/list-of-cities-and-towns-in-the-United-States-2023068

所以我已经尝试了CSVed程序,但是很难放置我不需要的每个国家等...

使用此VBA代码,他们将删除具有特定值的原始数据:

Sub Delete_All_Rows_IF_Cell_Contains_Certain_String_Text()
    Dim lRow As Long
    Dim iCntr As Long
    lRow = 1000
    For iCntr = lRow To 1 Step -1
        If Cells(iCntr, 3).Value = "Certain data to delete here" Then
            Rows(iCntr).Delete
        End If
    Next
End

是否可以不删除而是保存所有原始数据,但是值必须为几个,对此可以有帮助吗?

1 个答案:

答案 0 :(得分:0)

一种简单的方法是在单独的工作表中列出要保留的位置,然后在初始数据中添加额外的列,然后执行VLOOKUP(或INDEX/MATCH) ,然后过滤并删除。对于一次性过程,这就是我要做的。

对于vba解决方案,类似这样,但是您仍然需要在单独的工作表中列出可接受位置的列表:

Sub setDeleteNonUsa()
'Assuming 4 columns:
'A: [names]
'B: [location]
'C: [gender]
'D: [email]

Dim wb As Workbook: Set wb = ActiveWorkbook 'Alternative options: ThisWorkbook or Workbooks("book name")

Dim wsData As Worksheet: Set wsData = wb.Worksheets("Sheet1")
Dim wsLocs As Worksheet: Set wsLocs = wb.Worksheets("Sheet2")

'Declare and set the variable to hold the last row values
Dim lRowData As Long: lRowData = wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row
Dim lRowLocs As Long: lRowLocs = wsLocs.Cells(wsLocs.Rows.Count, "A").End(xlUp).Row

'Declare and set an array to hold the current data (Column A:D, Sheet1)
Dim arrData As Variant: arrData = wsData.Range("A1:D" & lRowData) 'allocate the data to the array

'Declare and set an array to hold the acceptable locations (column A, Sheet2)
Dim arrLocs As Variant: arrLocs = wsLocs.Range("A1:A" & lRowLocs) 'allocate the locations to the array

'Process the data
Dim Rd As Long, Rl As Long
For Rd = UBound(arrData) To LBound(arrData) + 1 Step -1 'Iterate through each row of the data, skipping headings
    For Rl = LBound(arrLocs) + 1 To UBound(arrLocs) 'Iterate through each row of the locs, skipping headings
        If arrData(Rd, 2) = arrLocs(Rl, 1) Then Exit For 'location match, skip to next
        If Rl = UBound(arrLocs) Then wsData.Cells(Rd, 1).EntireRow.Delete 'we got to last one, no location match
    Next Rl
Next Rd

End Sub