2010-06-14 69 views
1

我有一張包含房屋地址數據行的主表,其中一列是「狀態」列。我在同一份文件中有50份其他表,對應於美國50個州的每個州。我想要發生的事情:當我在主表單中輸入一個地址並輸入一個狀態(例如「CA」或「California」)時,我希望它自動填充具有該地址的「CA」表單。謝謝!用其他表中的數據填充新表格

回答

1

幾個假設這裏:

1)國家字段是最後一個被填充,這樣,一旦你進入狀態,就可以立即將地址複製到正確的工作表。

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個不同的工作表中複製數據?這看起來非常低效並且容易出錯。除非你需要這樣做,因爲一個非常具體的原因,我會非常強烈建議反對它。

如果你需要在某些時候顯示或使用單獨的狀態地址,那麼我會看看過濾主要地址列表。