Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 在所有excel工作表上运行脚本_Vba_Excel - Fatal编程技术网

Vba 在所有excel工作表上运行脚本

Vba 在所有excel工作表上运行脚本,vba,excel,Vba,Excel,我有一个脚本,它搜索一个已定义的字符串,并在找到该列时删除该列。我想在工作簿中的所有工作表上运行相同的搜索。到目前为止,我已经尝试过这样设置。但它将仅在活动工作表上运行 Sub RunMacroOnAllSheetsToRight() For i = ActiveSheet.Index To Sheets.Count Call MyFunction(i) Next i End Sub Function MyFunction(i) Dim c As Range

我有一个脚本,它搜索一个已定义的字符串,并在找到该列时删除该列。我想在工作簿中的所有工作表上运行相同的搜索。到目前为止,我已经尝试过这样设置。但它将仅在活动工作表上运行

Sub RunMacroOnAllSheetsToRight()
For i = ActiveSheet.Index To Sheets.Count
    Call MyFunction(i)
Next i
End Sub


Function MyFunction(i)
Dim c As Range
            Dim str As String

            str = "SearchStringHere"

            For Each c In ActiveSheet.UsedRange
               If InStr(c.Value, str) > 0 Then
               c.EntireColumn.Delete Shift:=xlToLeft
               End If
            Next c

End Function

脚本现在循环执行,但由于某些原因,只删除单个列。需要能够匹配和删除每个工作表中的多个列。

您只需在“函数”中更改ActiveSheet,它就会更好

顺便说一句:你可以有一个带参数的Sub(如下所示),并且只有当你有一个输出结果(在你的例子中没有)时才需要一个函数

2主要变化: -添加了Set Ws=Nothing以释放Ws -更改了通过列的增量,因为当删除越来越多的列时,您将无法分析下一列(j+1),即现在的列(j)


对本书中的每个ws使用
。工作表
循环此文件的可能副本非常有效,但只会从每张工作表中删除一列。如果标识的列多次出现,则必须重新运行脚本。这可以纠正吗?添加一个布尔值来设置和重置操作的可能性可能会起作用,您需要帮助吗?请!我现在边走边学。或者,我可以通过添加多个搜索字符串来实现。只要容易,我会在不到24小时内完成修改,谢谢!我可能会尝试用另一个宏循环多次。
Sub RunMacroOnAllSheetsToRight()
Application.ScreenUpdating = False
For i = ActiveSheet.Index To Sheets.Count
    Column_Delete i, "SearchStringHere"
Next i
Application.ScreenUpdating = True
End Sub


Sub Column_Delete(ByVal Sheets_Index As Integer, ByVal Str_to_Find As String)

Dim Ws As Worksheet
Set Ws = Worksheets(Sheets_Index)


Dim EndColumn As Integer
EndColumn = Ws.Cells(1, Columns.Count).End(xlToLeft).Column

'descending travel of the columns as we are going to delete some of them
For j = 1 To EndColumn
    If InStr(Ws.Cells(1, EndColumn - j + 1), Str_to_Find) > 0 Then
        Ws.Columns(EndColumn - j + 1).EntireColumn.Delete Shift:=xlToLeft
    End If
Next j

'Don't forget to free Ws (like I did...)
Set Ws = Nothing

End Sub