Closed. This question needs details or clarity。它当前不接受答案。












想改善这个问题吗?添加详细信息,并通过editing this post阐明问题。

3年前关闭。



Improve this question




我正在尝试使用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

最佳答案

我建议摆脱错误处理程序,而为每种情况编写代码:

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
  • (如果未找到)请尝试找到“NRP”
  • (如果找到),相应地设置lnCol
  • (如果未找到),然后传递一个消息框,该消息框既没有找到,也没有
    中止
  • 关于excel - 在VBA公式中使用IFERROR ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46958419/

    10-15 11:26