Excel工作簿故障

时间:2016-11-09 06:41:06

标签: excel vba excel-vba

在我进入循环之前,一切都很好。

一旦我进入循环,它会经历它循环将名字和姓氏调整为两个不同的列,但是,由于某种原因,它给了我一个错误。我无法弄清楚原因。

以下代码:

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)

1 个答案:

答案 0 :(得分: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