工作簿之间的VBA切换提供错误的单元格引用

时间:2014-06-19 13:19:55

标签: excel vba excel-vba

简介

我目前正在处理一个VBA代码,该代码将数据从工作簿中的一个工作表导入另一个工作簿中的工作表。基本上,此复制粘贴过程的目标是将范围从TargetWorkbook中的A2复制到SourceWorkbook中的A2。这个程序出错了。

代码:

Sub Import()

Worksheets("Alle borgere").Range("A2:BZ9999").ClearContents

Dim TargetWorkbook, SourceWorkbook As String
Dim StartSKUrow, StopSKUrow As Integer
Dim CellValueString, RangeTarget As String
Dim QuoteButton

Dim val(10) As Double
On Error Resume Next

' Save workbook name and search for the old quote workbook
Sheet9.Select ' quote sheet
SourceWorkbook = ActiveWorkbook.Name

' check what workbook to use as old quote
Do
    ActiveWindow.ActivateNext
    TargetWorkbook = ActiveWorkbook.Name

    If TargetWorkbook = SourceWorkbook Then
       MsgBox ("Åben venligst rette dokument")
       'Sheet9.Protect
      'Exit Sub
       End
    End If

    QuoteButton = MsgBox("Er dette data til import?", vbYesNoCancel)

    Select Case QuoteButton
    Case 2 ' cancel
        End
    Case 6 ' yes
        Exit Do
    Case 7 ' no
        TargetWorkbook = ""
    Case Else
    End Select

Loop Until TargetWorkbook = SourceWorkbook

 Application.ScreenUpdating = True

StartSKUrow = 0
StopSKUrow = 0
If QuoteButton = 6 Then ' Yes - start the import from this sheet

         '!!The problem is here!!
        Workbooks(TargetWorkbook).Activate
        Sheets("Alle borger").Range("A2").Select
        Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select

        Selection.Copy
        ActiveSheet.Paste
        Workbooks(SourceWorkbook).Activate
        Sheet9.Visible = xlSheetVisible
        Sheet9.Activate
        Range("A2").Select
        Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False


End If

Sheet1.Activate
   Application.ScreenUpdating = True

End Sub

注意!!问题出在这里,表明存在问题"。

问题: 基本上,当执行以下代码时,TargetWorkbook中的选定区域不是由Range("A2").Select驱逐,而是由TargetWorkbook中的最后一次单击驱逐。

Workbooks(TargetWorkbook).Activate
Sheets("Alle borger").Range("A2").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select

为什么你认为是这种情况?

0 个答案:

没有答案