VBAselect与值匹配的列并将数据复制到其他工作簿

我有两个excel工作簿, rh总结 。 我有摘要中的代码检查rh文件,以find一个特定的列基于其中的文本。 我需要find这些列,复制它们并将数据发送到汇总表。

Sub Main() ' Declare hr workbook file Dim rh As Excel.Workbook ' initialise hr workbook file Set rh = Workbooks.Open("C:\Users\AC74338\Desktop\ac\rh") 'select the rh file rh.Select 'select the open worksheet Sheets("Open").Select ' search for the column header that matches eg "Org Level 6" OrgLevel6 = WorksheetFunction.Match("Org Level 6", Rows("1:1"), 0) OrgLevel7 = WorksheetFunction.Match("Org Level 7", Rows("1:1"), 0) 'activate this workbook where the code is ThisWorkbook.Activate 'paste the data that was copied to this workbook in the NxNOpen worksheet ThisWorkbook.Sheets("NxNOpen").Columns(OrgLevel6).Copy Destination:=Sheets("Sheet2").Range("A1") ThisWorkbook.Sheets("NxNOpen").Columns(OrgLevel7).Copy Destination:=Sheets("Sheet2").Range("B1") End Sub 

我已经debugging并将数据分配给OrgLevel6variables时出现错误。 任何人有任何build议如何解决这个问题? 对VB不是很了解,所以可能是一个简单的错误。

当您在VBA中使用WorksheetFunction ,您仍然需要使用VBA Range引用,而不是使用Rows(1:1)您需要引用VBA代码中的行。 例如:

 OrgLevel6 = WorksheetFunction.Match("Org Level 6", rh.Sheets("Open").Rows(1), 0) OrgLevel7 = WorksheetFunction.Match("Org Level 7", rh.Sheets("Open").Rows(1), 0) 

我已经testing了你的OrgLevel6 =行,它可以在一张纸上正常工作,所以有可能在没有正确的纸张的情况下执行,因此无法find“组织级别6”。

尝试更改Sheets("Open").Select Sheets("Open").Activate

请尝试下面的代码:

 Sub Main() ' Declare hr workbook file Dim rh As Excel.Workbook Dim sum As Excel.Workbook Dim b As Integer ' initialise hr workbook file Set rh = Workbooks.Open("C:\Users\AC74338\Desktop\ac\rh") Set sum = ThisWorkbook b = 1 lcol = rh.Sheets("Open").Cells(1, Columns.Count).End(xlToLeft).Column For i = 1 To lcol If rh.Sheets("Open").Cells(1, i).Value = "Org Level 6" Or "Org Level 7" Then rh.Sheets("Open").Columns(i).Copy sum.Sheets("Sheet2").Cells(1, b) b = b + 1 End If Next i End Sub 

Rows("1:1")更改为Rows(1)

您正在名为“打开”的工作表上应用匹配function,但是您正在复制表单“NxNOpen”中的数据。 右栏,错误的表格