无法选择一个单元格 - 非常奇怪

时间:2016-01-08 23:08:29

标签: excel-vba vba excel

请帮忙! 我的代码的最后一行

'Sheets("Original Data from Server").Cells(4, 2).Select

不行!继续收到错误"选择范围类的方法失败' 每当我只运行那一行时,它就完美了。 但每当我运行剩下的代码时,我都会收到错误。

没有人可以帮我解决这个问题!

Sub FormatAdjacencyReport()

Dim iLastRow As Integer '<-- Interger for Counting Number of Rows
Dim iLastColumn As Integer '<-- Interger for Counting Number of Columns
Dim OriginalOutput As Worksheet '<-- Sheet Containing Orignal Report
Dim AdjacencyData As Worksheet '<-- Sheet Crated for Final Output

Set OriginalOutput = ActiveWorkbook.Worksheets(1)
OriginalOutput.Name = "Original Data from Server"

'Determines how many different rows we have in original output
iLastRow = Range("B1").Rows.End(xlDown).Row

'Txt to Columns for Each Row
For i = 2 To iLastRow
    Sheets("Original Data from Server").Cells(i, 5).TextToColumns DataType:=xlDelimited, _
    ConsecutiveDelimiter:=True, Space:=True
Next i

'Create a new sheet for our output
Set AdjacencyData = Sheets.Add
AdjacencyData.Name = "Adjacency Data Output"

'Need to Paste the Entire List of Store Numbers into a New Tab


iLastColumn = Sheets("Original Data from Server").Cells(2, 1).Columns.End(xlToRight).Column
'Sheets("Original Data from Server").Cells(4, 2).Select


End Sub

2 个答案:

答案 0 :(得分:2)

在调用该工作表上的选择之前,您需要将焦点设置回Sheets(“来自服务器的原始数据”)。所以把行'Sheets(“来自服务器的原始数据”)放在最后一行之前。当正在执行线投掷错误时,焦点在另一张纸上。

答案 1 :(得分:0)

为避免此类错误,我建议您暂时停止使用select和/或activate,并且只在绝对必要时才使用它。
您的代码可能如下所示:

Sub FormatAdjacencyReport()
    Dim iLastRow As Long '<--  for Counting Number of Rows
    Dim iLastColumn As Long '<--  for Counting Number of Columns
    Dim OriginalOutput As Worksheet '<-- Sheet Containing Orignal Report
    Dim AdjacencyData As Worksheet '<-- Sheet Crated for Final Output

    Set OriginalOutput = ActiveWorkbook.Worksheets(1)
    OriginalOutput.Name = "Original Data from Server"

    'Determines how many different rows we have in original output
    iLastRow = OriginalOutput.Range("B1").End(xlDown).Row  ' changed
    iLastColumn = OriginalOutput.Range("A2").End(xlToRight).Column  ' changed

    'Txt to Columns for Each Row
    For i = 2 To iLastRow
        OriginalOutput.Cells(i, 5).TextToColumns DataType:=xlDelimited, _
        ConsecutiveDelimiter:=True, Space:=True
    Next i

    'Create a new sheet for our output
    Set AdjacencyData = Sheets.Add
    AdjacencyData.Name = "Adjacency Data Output"

    'Need to Paste the Entire List of Store Numbers into a New Tab

    ' OriginalOutput.Activate -- not needed
    ' OriginalOutput.Cells(4, 2).Select  -- not needed
    OriginalOutput.Range("B4:B17").Value = AdjacencyData.Range("A10:A23") ' direct copy!

End Sub

1-只要您处理多个工作表或工作簿,就可以使用合格的范围/单元格。查看确定iLastRow的行 2-将表限制计算保存在一个地方(限制一旦确定)
3-避免使用明确的限定词(Sheets("Original Data from Server").)来支持指定的变量(OrignalOutput)。这样,您就可以在一个位置完全限定(使用工作簿名称和工作表名称)。想象一下,你以后要更改工作表名称...
4-使用从范围到范围的直接分配进行复制。这避免了引用问题(如果使用限定符!),并且剪贴板内容保持不变。