VBA根据内容保存单元格地址(并非总是有效)

时间:2018-08-28 01:25:34

标签: excel vba excel-vba

我一直在尝试建立一个模块,该模块从一个Excel文件复制数据并将其粘贴到另一个文件中。复制文件中的列将被随机打乱,我需要使用下面显示的代码在开始时确定它们的位置。

我的问题是我的代码有时可以工作(CopyCell_2 = C1等),但有时也可以工作(CopyCell_2为空),我不知道为什么。

这里的任何见解将不胜感激。

Option Explicit

Sub UpdateGroundData()

' Find last row
Dim LastRow_1 As Long      ' Set up variable                                                                       
LastRow_1 = Workbooks("GroundData").Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row                ' Find last non-blank row

' Find the right copyranges
With Workbooks("GroundData")
    Dim cell As Range
    Dim CopyCell_2 As Variant, CopyCell_3 As Variant, CopyCell_4 As Variant, CopyCell_5 As Variant
    Dim CopyCell_6 As Variant, CopyCell_7 As Variant, CopyCell_8 As Variant, CopyCell_9 As Variant
    For Each cell In Range("C1:J1")
        If InStr(cell.Text, "ADVANCE SPEED") > 0 Then
            CopyCell_2 = cell.Address
        ElseIf InStr(cell.Text, "AMOUNT CENTER FLUSHING") > 0 Then
            CopyCell_3 = cell.Address
        ElseIf InStr(cell.Text, "CUTTIG WHEEL ROTATION SPEED") > 0 Then
            CopyCell_4 = cell.Address
        ElseIf InStr(cell.Text, "DENSITY EXCAVATING CHAMBER") > 0 Then
            CopyCell_5 = cell.Address
        ElseIf InStr(cell.Text, "PRESSURE EXCAVATING CHAMBER 6 (LEFT TOP)") > 0 Then
            CopyCell_6 = cell.Address
        ElseIf InStr(cell.Text, "PRESSURE WORKING CHAMBER") > 0 Then
            CopyCell_7 = cell.Address
        ElseIf InStr(cell.Text, "SHIELD ARTICULATION CONTACT FORCE") > 0 Then
            CopyCell_8 = cell.Address
        ElseIf InStr(cell.Text, "TORQUE CUTTING WHEEL") > 0 Then
            CopyCell_9 = cell.Address
        End If
    Next cell
End With

编辑:

附有一张GroundData表

IMG1

1 个答案:

答案 0 :(得分:0)

当您提到“ 代码有时会起作用”,但“ 有时也会失败”时,通常的罪魁祸首是Range引用不合格,而{{ 1}}和/或ActiveWorkbook是隐含的。

在这种情况下,您实际上并没有使用ActiveSheet块,该块本身应包含一个With...End With引用。我假设它将是第一个Worksheet。 基于Worksheet行。

然后修改您的LastRow_1 = Workbooks("GroundData").Worksheets(1)...

With...End With

请注意,With Workbooks("GroundData").Worksheets(1) ... For Each cell In .Range("C1:J1") ... Next cell End With 前面的.-现在其Range("C1:J1")Workbook已完全合格,并且使用了Worksheet块。

作为另一项改进,您可以在With...End With内移动LastRow_1行,因为它引用了相同的With...End WithWorkbook