在VBA中匹配两个字符串,将其他单元格值传输到不同的位置

在VBA中匹配两个字符串,将其他单元格值传输到不同的位置,vba,excel,Vba,Excel,我正在编写一个宏,它利用一个userform来定义一个我以后需要在程序中引用的值(Val1)。宏需要进入特定的电子表格,查看几个标题,如果值匹配,则需要复制该列中的所有数据,并将其粘贴到同一工作簿中的不同电子表格中 目前,我得到了一份工作 运行时错误1004“选择范围类的方法失败” 在单元格的.End(xlDown)处选择 public NewSheetName as string, val1 as string Dim f As Range Set f = ThisWorkbook.S

我正在编写一个宏,它利用一个userform来定义一个我以后需要在程序中引用的值(Val1)。宏需要进入特定的电子表格,查看几个标题,如果值匹配,则需要复制该列中的所有数据,并将其粘贴到同一工作簿中的不同电子表格中

目前,我得到了一份工作

运行时错误1004“选择范围类的方法失败”

单元格的.End(xlDown)处选择

public NewSheetName as string, val1 as string
    Dim f As Range
Set f = ThisWorkbook.Sheets(1).Range("B1:L1")

For Each cell In f
    If cell = val1 Then
    cell.End(xlDown).Select
    selection.Copy Destination:=ThisWorkbook.Sheets(NewSheetName).Range("B1")
'NewSheetName is defined elsewhere
    End If
Next

我相信这就是你想要的。
我首先找到
match
,这将是您正在搜索的内容的列字母

然后复制列并粘贴值。
不需要循环

on error resume next ' if nothing is found it creates an error
match = Split(Cells(1, Cells(1, 1).EntireRow.Find(what:=val1, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, searchdirection:=xlNext, MatchCase:=True).Column).Address(True, False), "$")(0)
on error goto 0
if match = "" or match > "L" then
    msgbox "nothing found in range"
else
    Range(match & ":" & match).Copy ' copies column "E:E" for example
    ThisWorkbook.Sheets(NewSheetName).Range("B1").Select ' selects output cell
    ActiveSheet.Paste ' paste
end if
  • 创建一个包含2个工作表的新Excel工作簿
  • 在第一个单词中,在范围
    B1:L1
    中写“某物”3-4次
  • 在范围
    B2:L10
    中写入其他随机内容
运行以下命令:

Option Explicit

Public Sub TestMe()

    Dim val1 As String: val1 = "something"
    Dim cell As Range
    Dim f As Range

    Set f = Worksheets(1).Range("B1:L1")

    For Each cell In f
        If cell = val1 Then
            cell.End(xlDown).Copy Destination:=Worksheets(2).Range(cell.Address)
        End If
    Next

End Sub

它在第一张工作表的
范围(B1:L1)
中循环,如果在那里找到单词
something
,它会将范围复制到第二张工作表。

以下是一种避免循环的方法:

Sub foo(ByVal sVal1 As String, ByVal sSheetName As String)
    Dim c As Range

    Set c = ThisWorkbook.Sheets(1).Range("B1:L1").Find(what:=sVal1)
    If Not c Is Nothing Then
        Range(c, c.End(xlDown)).Copy Destination:=ThisWorkbook.Sheets(sSheetName).Range("B1")
    End If
End Sub

什么是
val1
NewSheetName
?它们有定义吗?在上面的公开声明中有定义。NewSheetName派生自inputbox(创建新工作表),val1派生自userform中的字段。。。哪两个?据我所知,您只是在指定范围的第一行中搜索val1?
cell.End(xlDown)。Select
选择单个单元格。是的,尝试匹配“val1”和范围“f”中的单元格。