我正在尝试使用VBA将列从一个工作簿复制到另一个工作簿,具体取决于列标题。但是,每次都会出现Run-time error '9': Subscript out of range
错误。
我正在关注SO 1 2提出的另外两个问题。但是,它失败的代码行似乎适用于有问题的其他OP [2]。
Sub Autofill()
Dim sourceColumn As Range, target_column As Range
'read csv and convert to excel
tx_design_file_name = ThisWorkbook.Sheets("Cover").Range("E10").Value
Set tx_design_file_workbook = Workbooks.Open(tx_design_file_name)
tx_design_file_workbook.SaveAs FileName:=ThisWorkbook.Path & "\Input\data.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
tx_design_file_workbook.Close savechanges:=False
Set compt_template = Workbooks.Open(ThisWorkbook.Path & "\Template\CoMPT_Convert_Template.xlsx")
Set target_column = compt_template.Worksheets(1).Columns("A")
Set data_excel_workbook = Workbooks.Open(ThisWorkbook.Path & "\Input\data.xlsx")
Dim aCell As Range
With data_excel_workbook.Worksheets(1)
Set aCell = .Rows(1).Find(What:="SiteName", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
aCell.EntireColumn.Cut Destination:=target_column
Else
MsgBox "SiteName not found"
End If
End With
output_path_name = ThisWorkbook.Path & "\Output\CoMPT_Convert.xlsx"
compt_template.SaveAs (output_path_name)
'target_column.SaveAs (output_path_name)
End Sub
答案 0 :(得分:0)
阅读您的评论后,我认为您输入错误:
Sub Autofill()
Dim sourceColumn As Range, target_column As Range
'read csv and convert to excel
tx_design_file_name = ThisWorkbook.Sheets("Feuil1").Range("E10").Value
Set tx_design_file_workbook = Workbooks.Open(tx_design_file_name)
tx_design_file_workbook.SaveAs Filename:=ThisWorkbook.Path & "\Input\data.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
tx_design_file_workbook.Close savechanges:=False
Set compt_template = Workbooks.Open(ThisWorkbook.Path & "\Template\CoMPT_Convert_Template.xlsx")
Set target_column = Workbooks("CoMPT_Convert_Template").Worksheets(1).Range("A" & ActiveSheet.Cells(1048576, 1).End(xlUp).row)
Set data_excel_workbook = Workbooks.Open(ThisWorkbook.Path & "\Input\data.xlsx")
Dim aCell As Range
With data_excel_workbook.Worksheets(1)
Set aCell = .Rows(1).Find(What:="SiteName", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
aCell.EntireColumn.Cut Destination:=target_column
Else
MsgBox "SiteName not found"
End If
End With
output_path_name = ThisWorkbook.Path & "\Output\CoMPT_Convert.xlsx"
compt_template.SaveAs (output_path_name)
'target_column.SaveAs (output_path_name)
End Sub