我有一个宏来搜索不同工作表上的值。这工作正常, 但问题是我想要整行的值,而不仅仅是我正在寻找的值。
代码如下:
Sub SearchFolders()
Dim xFso As Object
Dim xFld As Object
Dim xStrSearch As String
Dim xStrPath As String
Dim xStrFile As String
Dim xOut As Worksheet
Dim xWb As Workbook
Dim xWk As Worksheet
Dim xRow As Long
Dim xFound As Range
Dim xStrAddress As String
Dim xFileDialog As FileDialog
Dim xUpdate As Boolean
Dim xCount As Long
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "select folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
xStrSearch = "searched value"
xUpdate = Application.ScreenUpdating
Application.ScreenUpdating = False
Set xOut = Worksheets.Add
xRow = 1
With xOut
.Cells(xRow, 1) = "book"
.Cells(xRow, 2) = "sheet"
.Cells(xRow, 3) = "cell"
.Cells(xRow, 4) = "search value"
Set xFso = CreateObject("Scripting.FileSystemObject")
Set xFld = xFso.GetFolder(xStrPath)
xStrFile = Dir(xStrPath & "\*.xls*")
Do While xStrFile <> ""
Set xWb = Workbooks.Open(Filename:=xStrPath & "\" & xStrFile, UpdateLinks:=0, ReadOnly:=True, AddToMRU:=False)
For Each xWk In xWb.Worksheets
Set xFound = xWk.UsedRange.Find(xStrSearch)
If Not xFound Is Nothing Then
xStrAddress = xFound.Address
End If
Do
If xFound Is Nothing Then
Exit Do
Else
xCount = xCount + 1
xRow = xRow + 1
.Cells(xRow, 1) = xWb.Name
.Cells(xRow, 2) = xWk.Name
.Cells(xRow, 3) = xFound.Address
.Cells(xRow, 4) = xFound.Value
End If
Set xFound = xWk.Cells.FindNext(After:=xFound)
Loop While xStrAddress <> xFound.Address
Next
xWb.Close (False)
xStrFile = Dir
Loop
.Columns("A:D").EntireColumn.AutoFit
End With
MsgBox xCount & "Cells found", , "EA"
ExitHandler:
Set xOut = Nothing
Set xWk = Nothing
Set xWb = Nothing
Set xFld = Nothing
Set xFso = Nothing
Application.ScreenUpdating = xUpdate
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
我需要它来查找不同书籍中的值并返回找到所查找值的整行的信息。
最佳答案
根据我对“我想要整行的值”的含义的最佳猜测:
将整行作为 Range
对象访问
Dim rng As Range
Set rng = xFound.EntireRow
创建一个包含整行值的变量(尺寸为 (1 To 1, 1 To 16384)
):
Dim rngValue As Variant
rngValue = xFound.EntireRow.Value
MsgBox rngValue(1, 20) ' will display the value from column T
要单独访问行中的某些列:
MsgBox xFound.EntireRow.Cells(1, "T") ' will display the value from column T
MsgBox xFound.EntireRow.Range("T1") ' will display the value from column T
要将某些目标单元格设置为找到的行上某些单元格的值:
'Copy values from columns A to T from original row to columns D to W of the destination
.Cells(xRow, 4).Range("A1:T1").Value = xFound.EntireRow.Range("A1:T1").Value
要简单地查找发生查找的行号:
MsgBox xFound.Row
关于excel - 搜索值并返回 Excel 中的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308887/