我试图使用VBA从文件夹中的各种不同文件中复制信息,但是,在某些文件中,标题是“净零售价”"在一些" NRP"。
我的代码查找标题文本以查找列,然后从该列复制信息。我需要一种方法来搜索"净零售价格",然后如果它找不到搜索" NRP"。
到目前为止,我可以查找"净零售价",如果找不到,它会搜索" NRP"。但如果是相反的方向(即标题为净零售价),则会抛出错误。
Sub Test()
Dim wb As Workbook
Dim Masterwb As Workbook
Dim sh As Worksheet
Dim Mastersht As Worksheet
Dim PasteRow As Long
Dim lnRow As Long
Dim lnCol As Long
'Copy out NRP
lnRow = 3
On Error GoTo ErrorHandler
lnCol = sh.Cells(lnRow, 1).EntireRow.Find(What:="Net Retail Price", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
ErrorHandler:
lnCol = sh.Cells(lnRow, 1).EntireRow.Find(What:="NRP", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
sh.Range(Cells(lnRow + 2, lnCol), Cells(i, lnCol)).Copy
Mastersht.Range("F" & PasteRow).PasteSpecial xlPasteValues
End Sub
答案 0 :(得分:1)
我建议摆脱错误处理程序,而不是为每个场景编写代码:
Option Explicit
Sub Test()
Dim wb As Workbook
Dim Masterwb As Workbook
Dim sh As Worksheet
Dim Mastersht As Worksheet
Dim PasteRow As Long
Dim lnRow As Long
Dim lnCol As Long
'New variables
Dim i As Long
Dim rngFound As Range
'Copy out NRP
lnRow = 3
Set rngFound = sh.Cells(lnRow, 1).EntireRow.Find(What:="Net Retail Price", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If rngFound Is Nothing Then
Set rngFound = sh.Cells(lnRow, 1).EntireRow.Find(What:="NRP", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If rngFound Is Nothing Then
MsgBox "Couldn't find neither NRP nor Net Retail Price." & Chr(10) & "Aborting..."
Exit Sub
Else
lnCol = rngFound.Column
End If
Else
lnCol = rngFound.Column
End If
sh.Range(sh.Cells(lnRow + 2, lnCol), sh.Cells(i, lnCol)).Copy
Mastersht.Range("F" & PasteRow).PasteSpecial xlPasteValues
End Sub
的变化:
lnCol
lnCol
答案 1 :(得分:0)
我会在OnError处理程序中设置两个变量:
Col1: NPR;
Col2: Net Retail Price.
然后,我会提示宏在OnError处理程序中复制两列。
答案 2 :(得分:0)
我建议插入
On Error Goto 0
Exit Sub
到你的代码
Sub Test()
Dim wb As Workbook
Dim Masterwb As Workbook
Dim sh As Worksheet
Dim Mastersht As Worksheet
Dim PasteRow As Long
Dim lnRow As Long
Dim lnCol As Long
'Copy out NRP
lnRow = 3
On Error GoTo ErrorHandler
lnCol = sh.Cells(lnRow, 1).EntireRow.Find(What:="Net Retail Price", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
On Error Goto 0
sh.Range(Cells(lnRow + 2, lnCol), Cells(i, lnCol)).Copy
Mastersht.Range("F" & PasteRow).PasteSpecial xlPasteValues
Exit Sub
ErrorHandler:
lnCol = sh.Cells(lnRow, 1).EntireRow.Find(What:="NRP", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
Resume Next
End Sub
您还没有在
中定义变量ish.Range(Cells(lnRow + 2, lnCol), Cells(i, lnCol)).Copy
请注意,可能有另一个错误处理程序来处理第一个错误处理程序中的错误。