简体   繁体   English

用于根据单元格值查找和删除列的宏

[英]Macro to find and delete column based on cell value

I have two sheets in an Excel workbook. 我在Excel工作簿中有两张纸。 I would like a VBA code to search for the content of cell J19 in Sheet2 and delete the column with the matching cell in Sheet1. 我想要一个VBA代码在Sheet2中搜索单元格J19的内容,并在Sheet1中删除具有匹配单元格的列。 I have been searching all around Google to look for some VBA codes, but I haven't found anything yet that works. 我一直在Google各处搜索以查找一些VBA代码,但尚未找到任何有效的方法。

Does anybody here know how to do this? 这里有人知道怎么做吗? I have zero experience in VBA. 我在VBA中的经验为零。

You could try this code to perform such a task. 您可以尝试使用此代码执行此类任务。

Sub FindMatchAndThenDeleteColumn()

    FindContent = Worksheets("Sheet2").Range("J19")

    For Each Cell In Worksheets("Sheet1").UsedRange.Cells
        If Cell.Value = FindContent Then Columns(Cell.Column).Delete
    Next

End Sub

Put the code above in your workbook's module . 将上面的代码放入工作簿的模块中 Note that FindContent and Cell are randomly chosen here, you can use any names. 注意,在这里随机选择FindContentCell ,您可以使用任何名称。 I use 我用

   For Each Cell In Worksheets("Sheet1").UsedRange.Cells 

to loop through every cell that is in use in Sheet1 . 遍历Sheet1中使用的每个单元格。 It will check everything in the range from cell A1 to the last cell with data (the bottom right-most cell). 它将检查从单元格A1到最后一个具有数据的单元格(最右下的单元格)范围内的所有内容。 If the content of cell J19 is a text, you can declare the variable FindContent as a String type, ie Dim FindContent As String . 如果单元格J19的内容是文本,则可以将变量FindContent声明为String类型,即Dim FindContent As String If it's a number, you can declare it as a Long type or a Single type or any number type that fits the content. 如果是数字,则可以将其声明为Long类型或Single类型或适合其内容的任何数字类型。 Here I don't declare it which means it defaulting to a Variant type. 在这里,我没有声明它,这意味着它默认为Variant类型。 And since you're a beginner in VBA, you may learn it from Excel Easy . 而且,由于您是VBA的初学者,因此可以从Excel Easy中学习它。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM