运行时错误'1004'

时间:2014-02-19 15:33:43

标签: vba runtime-error

我是VBA的新手。我正在研究一个项目,该项目将验证输入表格的数据的长度和格式。我将扩展代码以包括所有潜在标题的验证(电话号码,地址,后缀等)。但是,我在这行代码中接收到运行时错误1004,“字符(col).NumberFormat =”0“”在phonenumbers子中。如果我评论该行,我会在下一行收到相同的错误。寻求帮助/解释为什么会发生这种情况以及如何解决。

谢谢!

Option Explicit

Sub DataVerification()
   Dim i As Long
   Dim rw As Long
   Dim col As Long
   Dim rng As Range

'Set cell background color to nothing
ActiveSheet.Cells.Interior.ColorIndex = xlNone

'loop through header row A10:F10 to determine which column needs validation
 For i = 1 To 6
   With Sheets("Sheet2")
      If UCase(.Cells(10, i).Value) = "PHONE NUMBERS" Then
         Call PhoneNumbers
      ElseIf UCase(.Cells(10, i).Value) = "ADDRESSES" Then
         Call Addresses
      ElseIf UCase(.Cells(10, i).Value) = "SUFFIXES" Then
         Call Suffixes
      Else
         MsgBox ("No data entered")
         Exit For
      End If
   End With
 Next i


'Phone numbers text found?
If col = 0 Then
   MsgBox "Phone Numbers Header not found"
   Exit Sub
End If

'Set column format to number
Columns(col).NumberFormat = "0"


'set up the start range, loop until we find an empty cell


'tidy up
Set rng = Nothing

 End Sub

 Sub PhoneNumbers()
Dim i As Long
Dim rw As Long
Dim col As Long
Dim rng As Range


 col = i

 'Set column format to number
 Columns(col).NumberFormat = "0"

 Set rng = Sheets("Sheet2").Cells(11, col)
 Do Until rng = ""
   If Not IsNumeric(rng.Value) Or Len(rng.Value) <> 11 Then

      'highlight cell
      rng.Interior.ColorIndex = 3 'red
   End If

   'get next row
   Set rng = rng.Offset(1, 0)
  Loop
 End Sub

1 个答案:

答案 0 :(得分:0)

在您的代码中,Col为零。列从索引1开始,试试这个:

  Col = 1
'Set column format to number
Columns(col).NumberFormat = "0"