【问题标题】:Fill New Sheets With Data From Other Sheets用其他工作表中的数据填充新工作表
【发布时间】:2011-03-03 16:13:41
【问题描述】:

我有一个主表,其中包含多行房屋地址数据,其中一列是“州”列。我在同一份文档中还有 50 张其他表格,对应于美国 50 个州中的每一个。我想要发生的事情:当我在主表中输入地址并进入一个州(比如“CA”或“California”)时,我希望它自动使用该地址填充“CA”表。谢谢!

【问题讨论】:

    标签: excel excel-2007 excel-formula vba


    【解决方案1】:

    这里有几个假设:

    1)State字段是最后填写的,这样一旦进入状态,就可以立即将地址复制到正确的工作表中。

    2) 您使用缩写输入您的州,并且您的工作表的名称与州缩写完全匹配。

    3) 州工作表的数据是连续的,从 A1 开始。

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        Const lngSTATECOLUMN As Long = 6
    
        Dim wks As Worksheet
        Dim lngNextAvailableRow As Long
    
        ' check that only a single cell is being changed '
        If Target.Areas.Count = 1 And Target.Cells.Count = 1 Then
    
            ' check that the cell being edited is in the state column '
            If Not Intersect(Target, Columns(lngSTATECOLUMN)) Is Nothing Then
    
                ' check that a two-character entry has been made in the state column '
                If Len(Target.Value) = 2 Then
    
                    ' turn off error checking in case it cannot find a matching worksheet '
                    On Error Resume Next
                    Set wks = ThisWorkbook.Worksheets(Target.Value)
                    On Error GoTo 0
    
                    ' continue if it found a worksheet with the same name as the state you input '
                    If Not wks Is Nothing Then
    
                        lngNextAvailableRow = wks.Range("a1").CurrentRegion.Rows.Count + 1
                        ActiveSheet.Range(Cells(Target.Row, 1), Cells(Target.Row, 6)).Copy _
                            wks.Range("A" & lngNextAvailableRow)
    
                    End If
                End If
            End If
        End If
    
    End Sub
    

    不过,我想问一下,为什么需要在 50 个不同的工作表中复制数据?这似乎非常低效且容易出错。除非您出于非常特定的原因需要这样做,否则我会非常强烈地建议您不要这样做。

    如果您在某些时候需要显示或使用单独的州地址,那么我会考虑过滤主地址列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多