Excel 宏删除包含可变文本的行

标签 excel vba search delete-row excel-2016

这是我第一次发帖。

我试图在 Excel 2016 中找到一种方法来清理文件夹列表,以便我只有父文件夹。

我有一个电子表格,其中 A 列是文件夹列表,包括它们的子文件夹。像这样:[仅供引用 - 每行中还有其他列,但它们与此示例无关]

\\server\share\root\subfolder1\
\\server\share\root\subfolder1\sub-subfolderA\
\\server\share\root\subfolder1\sub-subfolderB\
\\server\share\root\subfolder1\sub-subfolderC\
\\server\share\root\subfolder2\
\\server\share\root\subfolder2\other-subfolderA\
\\server\share\root\subfolder2\other-subfolderB\
\\server22\share\root\subfolder3\ham_sandwich\
\\server22\share\root\subfolder3\ham_sandwich\yet-another-subfolderA\
\\server22\share\root\subfolder3\and-another-subfolderA\
\\server22\share\root\subfolder3\and-another-subfolderB\

大约有 2500 行包含不同长度的文件夹,我的最终目标是只得到每个“集合”的顶级文件夹。例如:
\\server\share\root\subfolder1\
\\server\share\root\subfolder2\
\\server22\share\root\subfolder3\ham_sandwich\
\\server22\share\root\subfolder3\and-another-subfolderA\
\\server22\share\root\subfolder3\and-another-subfolderB\

我对此的逻辑如下(如果我忽略了任何内容,请纠正我):
See if the string in A1 is contained within the string in A2.
  If A2 contains the string, delete row 2.
  If it doesn't, move down to compare A2 with A3. [since we know A1 is now the only cell containing that top folder]
Rinse-and-repeat until the last populated row is reached.

我的问题是找出代码。我在网上看到各种关于搜索指定文本的代码片段,但没有任何使用变量的代码片段。我最初是在玩弄 IsNumber 和 Search 的公式组合,但它需要固定的文本来搜索,这会随着宏的进展而改变。

有人可以为此指出正确的方向吗?

最佳答案

假设顶级文件夹始终列在子文件夹之前:

k = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = k - 1 To 1 Step -1
    For j = k To i + 1 Step -1
        If InStr(Range("A" & j), Range("A" & i)) > 0 Then
            Rows(j).Delete
            k = k - 1
        End If
    Next j
Next i

关于Excel 宏删除包含可变文本的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936029/

相关文章:

excel - 将前 3 个字符更改为粗体格式

android 搜索 View 光标与工具栏的相同颜色不可见

javascript - 将特定 Excel 公式转换为 Javascript

xml - 如何处理excel宏中缺少的xml节点

vba - 在 Excel 2013 加载项中插入列失败并出现错误 438

正则表达式查找模式,然后插入模式

Javascript/JSON 对象数组搜索问题

mysql - 在mysql中搜索大量不断更新的文本

excel - WorksheetFunction.Sum 返回数字零

python - 将数据附加到现有的 Excel 电子表格