我在Excel 2010中使用VBA創建宏,以根據DOB和狀態單元(全部在同一工作簿中)將行從一個工作表移動到另一個工作表。Excel 2010 VBA - 不添加行
該宏檢查DOB對「截止」日期,如果該行通過,該行應附加到TSP表並從Sheet1中刪除。
如果未通過,則檢查該行的「狀態」單元是否存在狀態表。如果是這樣,那麼該行應該被追加到該工作表的末尾,並從Sheet1中刪除。
如果該行不符合這兩者中的任何一個,則只需手動進行檢查,因爲它缺少數據或數據輸入不正確。
除了將行附加到工作表外,所有工作都正常。它只是替換表格的最後一行,除了OH表格以外,因爲OH表格是出於任何原因工作的。
我的宏:
Sub Move()
'
' Move Macro
'
' Keyboard Shortcut: Ctrl+Shift+M
' Declare and set variables
Dim CBL_DATE
Dim totalrows, c
Set tsp_sheet = Sheets("TSP")
Set people = Sheets("Sheet1")
CBL_DATE = DateAdd("yyyy", -59.5, Date)
' Find total number of people to move
totalrows = people.UsedRange.Rows.Count
' Step through each row
For Row = totalrows To 2 Step -1
' Do not do anything if row is 1
If Row >= 2 Then
' Check for CBL cut off date and move to TSP sheet
If Cells(Row, 3).Value < CBL_DATE Then
tsp_sheet.Rows(tsp_sheet.UsedRange.Rows.Count + 1).Value = people.Rows(Row).Value
people.Rows(Row).Delete
Else
' Now we check for the state and if that worksheet exists, we copy to it and delete original
If SheetExists(Cells(Row, 2).Value) Then
Set st_sheet = Sheets(Cells(Row, 2).Value)
c = st_sheet.UsedRange.Rows.Count + 1
MsgBox Cells(Row, 2).Value & " " & c
st_sheet.Rows(c).Value = people.Rows(Row).Value
people.Rows(Row).Delete
End If
End If
End If
Next Row
End Sub
' End Sub Move()
我的表Sheet1中爲
Sheet 1 Name |State |DOB -------------------------- Tim |MI |10/2/1978 Bob |MI |10/5/1949 Suesan |TN |10/8/1978 Debra |OH |10/8/1975
所有其他工作表是空白,儘管我很想開始在第二行插入(或計數+ 1)。
編輯:我SheetExists()函數
' Public Function SheetExists
Public Function SheetExists(SheetName As String) As Boolean
Dim ws As Worksheet
SheetExists = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name = SheetName Then
SheetExists = True
Exit For
End If
Next ws
End Function
測試這一點,你可以請貼在第四indendation水平 – MikeD 2011-03-14 13:55:24
只是沒有用「SheetExists」功能,感謝 – 2011-03-14 14:54:40
啊感謝....正是我thougt ;-)我想我的答案仍然有效 – MikeD 2011-03-14 14:56:24