第一行出现问题,无法解决

时间:2019-06-12 07:52:28

标签: vba

我在代码的第一行中遇到了麻烦,问题是由于某种原因我无法修复它。

Sub Main(numgen as Integer, letras as String, letra as String, celda as String)
    Call coincidir
    Dim numgen As Integer
    numgen = 0
    numgen = coincidir("Total general; A8:Z8; 0")
    numgen = numgen + 1

    Dim letras(1 To 25) As String

    letras(1) = "A"
    letras(2) = "B"
    letras(3) = "C"
    letras(4) = "D"
    letras(5) = "E"
    letras(6) = "F"
    letras(7) = "G"
    letras(8) = "H"
    letras(9) = "I"
    letras(10) = "J"
    letras(11) = "K"
    letras(12) = "L"
    letras(13) = "M"
    letras(14) = "N"
    letras(15) = "O"
    letras(16) = "P"
    letras(17) = "Q"
    letras(18) = "R"
    letras(19) = "S"
    letras(20) = "T"
    letras(21) = "U"
    letras(22) = "V"
    letras(23) = "W"
    letras(24) = "Y"
    letras(25) = "Z"

    Dim letra As String
    letra = "w"
    letras(numgen) = letra

    Dim celda As String
    celda = letra + "8"

    Range("celda").Select
    ActiveCell.FormulaR1C1 = "Comisión"
End Sub

1 个答案:

答案 0 :(得分:0)

代码中有很多错误

  1. 删除Dim numgen As Integer(已在第一行中声明)
  2. 您正在一次连续地填充一个变量三遍,但可以在一行中完成
  3. 在填充数组后删除Dim letra As String
  4. 删除Dim celda As String(已在第一行中声明)
  5. 删除第一行的Dim letras As String
  6. 避免选择或激活范围
  7. 出于某种原因,您使用的只是一个单词字符串的公式填充了一个范围

应类似于:

Sub Main(numgen as Integer, letra as String, celda as String)
    Dim letras(1 To 25) as String
    Call coincidir
    numgen = coincidir("Total general; A8:Z8; 0") + 1 

    ''' ommitted

    letra = "w"
    letras(numgen) = letra

    celda = letra + "8"

    Workbooks(REF).Sheets(REF).Range("celda").Value= "Comisión"
End Sub

通常在调用子并希望将值传递给它时,按照Sub test(sheetname As String, Nr As Long)的方式进行操作。
例如:

Sub test()

i = Range("A1").Value
str = "Sheet3"

anothersub sheetname:= str, Nr:= i

End Sub

Sub anothersub(sheetname As String, Nr As Long)

Dim sht As Worksheet

Set sht = Sheets(sheetname)

For i = 0 To Nr
    MsgBox i
Next i

End Sub

您现在两次声明变量,这会导致错误