2016-11-09 73 views
0

一切都很好,直到我進入循環。Excel工作簿故障

一旦我進入循環,它將循環調整名字和姓氏到兩個不同的列中,但是出於某種原因,它會給我一個錯誤。我無法弄清楚爲什麼。下面

代碼:

Option Explicit 

Public Sub BreakNameApart() 
    'declare variables and assign address to Worksheet object variable 
    Dim intLocation As Integer, shtConsult As Worksheet, rngCell As Range 
    Set shtConsult = _ 
     Application.Workbooks("Franklin Consultants.xls").Worksheets("Consultants") 
    shtConsult.Columns("b").Insert 
    shtConsult.Range("a4").Value = "Last Name" 
    shtConsult.Range("b4").Value = "First Name" 
    shtConsult.Range("a4:b4").Font.Bold = True 
    'beginning in cell A5, seperate each full name into last and first name 
    Set rngCell = shtConsult.Range("a5") 
    Do Until rngCell.Value = "" 
     'find location of space 
     intLocation = InStr(1, rngCell.Value, " ") 
     'assign first name to appropriate cell in column B 
     rngCell.Offset(columnoffset:=1).Value = _ 
       Left(String:=rngCell.Value, Length:=intLocation - 1) 
     'assign last name to current cell 
     rngCell.Value = Mid(String:=rngCell.Value, Start:=intLocation + 1) 
     'assign the address of the cell in the next row to the rngCell variable 
     Set rngCell = rngCell.Offset(rowoffset:=1) 
    Loop 
    'adjust the width of columns A and B 
    shtConsult.Columns("a:b").AutoFit 


End Sub 

最值得注意的是它給了我在這裏的錯誤:

rngCell.Offset(columnoffset:=1).Value = _ 
       Left(String:=rngCell.Value, Length:=intLocation - 1) 
+0

看看val當錯誤被拋出時,'rngCell'的ue - 如果名稱中沒有空格,那麼'intLocation'將爲0,'LEFT'函數將嘗試從'rngCell'返回-1個字符導致錯誤。另一個可能的選擇 - 任何名字在開始時都有領先空間? –

回答

0

下面的代碼將在A列中的值拆分成多列A和B(最後和名字):

Option Explicit 

Public Sub BreakNameApart() 

    'declare variables and assign address to Worksheet object variable 
    Dim intLocation As Integer, shtConsult As Worksheet, rngCell As Range 

    Set shtConsult = _ 
     Application.Workbooks("Franklin Consultants.xls").Worksheets("Consultants") 

    shtConsult.Columns("b").Insert 
    shtConsult.Range("a4").Value = "Last Name" 
    shtConsult.Range("b4").Value = "First Name" 
    shtConsult.Range("a4:b4").Font.Bold = True 

    'beginning in cell A5, seperate each full name into last and first name 
    Set rngCell = shtConsult.Range("a5") 

    Do Until rngCell.Value = "" 
     'find location of space 
     intLocation = InStr(1, rngCell.Value, " ") 

     If intLocation > 0 Then ' space found 
      'assign first name to appropriate cell in column B 
      rngCell.Offset(0, 1).Value = Left(rngCell.Value, intLocation - 1) 

      'assign last name to current cell 
      rngCell.Value = Mid(rngCell.Value, intLocation + 1) 
     End If 
     'assign the address of the cell in the next row to the rngCell variable 
     Set rngCell = rngCell.Offset(1, 0) 
    Loop 

    'adjust the width of columns A and B 
    shtConsult.Columns("a:b").AutoFit 


End Sub 
+0

謝謝你的幫助。非常感激。 – TommyBoy116

+0

@TommyBoy116歡迎您,請標記爲答案 –