2015-08-25 33 views
0

因爲我是VBA的新手,並且我得到了表單名稱的順序未按預期排列的問題。 說:在工作簿中,sheet1的單元格A7 = sheet1的名稱A8 = sheet2的名稱,A9 = sheet3的名稱。我在工作簿上還有其他工作簿如何根據VBA中的圖紙順序爲行分配值

我寫了循環以從sheet()函數中將工作表名稱的值填充到工作表1的B7,B8,B9 。事情是如果我通過移動它們來更改工作表的順序,所以單元格A1,A2,A2的順序與工作表名稱不再匹配

請幫助修復我的代碼以使工作表名稱順序位於右側將因此

Private Sub Worksheet_Activate() 

Dim lrow As Long 
Dim i, j As Integer 
Dim sh As Worksheet 
Dim result As String 
Dim shName As String 
Dim sName As Long 

Sheets("sheet1").Range("B7:B9").Clear 
For i = 1 To Sheets.Count 
    With ThisWorkbook 
     Set sh = .Sheets(i) 
     shName = .Sheets(i).Name 
    '  MsgBox .Sheets(i).Name 
    End With 
    With sh 
     lrow = .Range("R" & .Rows.Count).End(xlUp).row 
    End With 
    Select Case shName 
     Case shName 

      '7 is the starting row at sheet 1 
      For j = 7 To lrow 
      If Sheets(shName).Cells(j, 1).value = shName(j) Then 
       worksheet.sheet("sheet1")cells(j,2).value ="something here" 
      endif 

     Next j 
    End Select 
End Sub 

回答

0

您需要使用Find功能查找工作表的名稱上worksheet1的範圍,然後你可以將行數放在它旁邊。

試試這個: -

Private Sub Worksheet_Activate() 

    Dim lrow As Long 
    Dim i, j As Integer 
    Dim sh As Worksheet 
    Dim result As String 
    Dim shName As String 
    Dim sName As Long 
    Dim rng As Range 

    Sheets("sheet1").Range("B7:B9").Clear 

    For i = 1 To Sheets.Count 
     With ThisWorkbook 
     Set sh = .Sheets(i) 
     shName = .Sheets(i).Name 
    '  MsgBox .Sheets(i).Name 
     End With 
     With sh 
      lrow = .Range("R" & .Rows.Count).End(xlUp).Row 
     End With 

     Set rng = Range("A7:A9").Find(shName) 

     'Only write something out if the sheet name is listed 
     If Not rng Is Nothing Then 
     rng.Offset(0, 1).Value = lrow 
     End If 
    Next 

End Sub 
相關問題