【发布时间】:2015-09-11 11:19:15
【问题描述】:
在我解释这段代码是关于什么之前稍微了解一下,首先用户将打开一个空的microsoft excel,然后用户将在一个宏上打开多个工作簿进入当前活动的excel,例如,如果用户选择要同时打开“book1”和“book2”,当前活动的 Excel 将打开它们并将它们拆分为一个以当前命名的工作簿命名的新工作表,例如工作表“book1”和工作表“book2”。
所以基本上这个程序使用户能够搜索一个字符串(在所有工作表中),然后在找出字符串的位置后,它将整个行+标题复制到一个以搜索字符串命名的新工作表。
例如,如果我搜索苹果,它将复制包含单词“apple”的整行并粘贴到名为“apple”的新工作表中,行和标题将被复制到那里,我需要现在要做的是创建一个新工作簿并创建一个以搜索字符串和之前命名的工作簿命名的新工作表。
就像我说的,我打开了工作簿“book1”和“book2”,如果搜索的单词来自工作表“book1”,宏会将搜索到的字符串复制到一个新工作簿中,一个名为“book1”的新工作表" 与信息。
我知道我已经以非常冗长的方式解释了这一点,如果您需要任何澄清,请告诉我。
Private Sub CommandButton5_Click()
Dim i As Long, nRowsAddePerSheet As Long, nRows As Long, _
nRowsMax As Long, nSheets As Long
Dim strSearch, strSearch2
Dim rg As Range, rgF As Range
Dim wks
Dim x
strSearch = Application.InputBox("Please enter the search string")
strSearch2 = Replace(strSearch, "*", "")
If Len(strSearch2) <= 0 Then
MsgBox "ABandon: Search string must not be empty."
Exit Sub
End If
Application.ScreenUpdating = False
nSheets = Sheets.Count
nRowsMax = ActiveSheet.Rows.Count
For x = 1 To nSheets
On Error Resume Next
Set wks = Worksheets(strSearch2)
If (Err) Then
Set wks = Worksheets.Add(After:=Sheets(Sheets.Count))
wks.Name = strSearch2
Err.Clear
End If
On Error GoTo 0
Sheets(x).Activate
Set rg = ActiveSheet.Cells(1).CurrentRegion
nRows = rg.Rows.Count
nRowsAddePerSheet = 0
For i = 1 To nRows
Set rgF = rg.Rows(i).Find(strSearch, , xlValues, xlWhole)
If Not rgF Is Nothing Then
If (nRowsAddePerSheet <= 0) Then
If (i <> 1) Then
rg.Rows(1).Copy wks.Range("A" & nRowsMax).End(xlUp).Offset(1, 0)
End If
End If
rg.Rows(i).Copy wks.Range("A" & nRowsMax).End(xlUp).Offset(1, 0)
nRowsAddePerSheet = nRowsAddePerSheet + 1
End If
Next
Next
Set rgF = Nothing
Set rg = Nothing
Set wks = Nothing
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
您在哪里搜索
apple?工作表或特定列中的任何位置? -
@SiddharthRout 工作簿中的任何位置,包括所有工作表。
标签: excel vba search excel-2010