0

我有一个宏程序来执行一些操作,如 Vlookup、删除列等。要更新的文件中会有一些工作表,并且每次工作表的名称和顺序可能不同。因此,我希望能够在每次使用宏时选择我想要的工作表。然而,我并没有成功......

这是宏。我希望 mySheet 是可变的。理想情况下,它可以提示我在该 wbSource 中选择我想要的工作表。但是,我遇到了错误。有谁知道我该怎么做?

提前致谢!

Sub Macro1()
    Dim file1 As String
    Dim file2 As String
    Dim wbSource As Workbook
    Dim wbLookup As Workbook
    Dim startRange As Range
    Dim mySheet As Worksheet
    Dim col As Range
    Dim Del As Range


    file1 = Application.GetOpenFilename(Title:="Select the file to update")
    If Len(Dir(file1)) = 0 Then Exit Sub
    file2 = Application.GetOpenFilename(Title:="Select the LOOKUP file")
    If Len(Dir(file2)) = 0 Then Exit Sub

    Set wbLookup = Workbooks.Open(file2)
    Set wbSource = Workbooks.Open(file1)
    Set mySheet = wbSource.Sheets(ActiveSheet.Name)



    On Error Resume Next
    Application.DisplayAlerts = False
    Set col = Application.InputBox _
             (Prompt:="Select Column.", _
                    Title:="Where do you want to insert the columns?", Type:=8)

    On Error GoTo 0

    Application.DisplayAlerts = True

    col.Resize(, 5).EntireColumn.Insert





    On Error Resume Next

    Application.DisplayAlerts = False

    Set Del = Application.InputBox _
    (Prompt:="Select Column.", _
     Title:="Which column to delimit?", Type:=8)


     On Error GoTo 0
    Application.DisplayAlerts = True


    Del.EntireColumn.Select '**  ERROR HERE!!

      Selection.TextToColumns _
      Destination:=Del, _
      DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, _
      Tab:=False, _
      Semicolon:=False, _
      Comma:=False, _
      Space:=False, _
      Other:=True, _
      OtherChar:="-"

     Del.Offset(0, 2).Delete
     Del.Offset(0, 1).Delete





  On Error Resume Next
    Set startRange = Application.InputBox("Select the first cell for the formula", "Autofill VLOOKUP", Type:=8)
    On Error GoTo 0
    If Not startRange Is Nothing Then
        Application.Goto startRange
         startRange.FormulaR1C1 = "=VLOOKUP('[" & wbSource.Name & "]" & mySheet.Name & "'!RC[-1],'[" & wbLookup.Name & "]NON SLL'!C1:C3,3,FALSE)"

    End If

End Sub
4

1 回答 1

0

评论的一些延续和对问题的可能解释......

您的代码没有出错。但是,您应该考虑一些逻辑错误。这行代码:

Set wbSource = Workbooks.Open(file1)

激活刚刚打开的工作簿(file1)。下一行:

Set mySheet = wbSource.Sheets(ActiveSheet.Name)

在刚刚打开的工作簿(file1)和当前处于活动状态的工作表中将变量设置为工作表。一般问题 - 这对于您代码的其他部分的逻辑是否正确?

于 2013-06-27T06:33:41.170 回答