简体   繁体   English

VBA中带有变量的Excel Vlookup公式

[英]Excel Vlookup Formula in VBA with Variables

I have Vlookup formula that I recorded in order to enter it to my VBA code with my variables. 我记录了Vlookup公式,以便使用变量将其输入到VBA代码中。 Somehow, one of the variables is not working good with my formula. 不知何故,这些变量之一不适用于我的公式。 sometimes the lastcol from type integer variable is 13 instead of 12 and sometimes its empty and I get 有时类型整数变量的lastcol是13而不是12,有时它是空的,我得到

Run time error 1004. 运行时错误1004。

I am not sure that I entered right the variables into the formula in the code. 我不确定我是否在代码中的公式中正确输入了变量。 The vlookup takes its data from the Visual worksheet (VisualWS variable). vlookup从Visual工作表(VisualWS变量)获取其数据。

this is the code where i'm stuck: 这是我卡住的代码:

Public myExtension As String
Public FullPath As String
Public VisualWB As Workbook
Public VisualWS As Worksheet
Public LR As Long
Public lastcol As Integer
Public MonCol As Integer
Public Table As Range
Public SigilDes As Integer
Public LR_Over As Long

Sub Analyze_1()

Call initialize

With OverWS

    LR_Over = .Cells(Rows.Count, "A").End(xlUp).Row
    .Range("M1").Value = "workdays"
    .Range("M2:M" & LR_Over).FormulaR1C1 = "=VLOOKUP(RC[-12],visual!R2C1:R " & LR & " C " & lastcol & "," & lastcol & ",FALSE)"

End With

this is the initialize sub: 这是初始化子:

Sub initialize()

Set MainWB = ThisWorkbook
Path = ThisWorkbook.Path
Set ListsWS = MainWB.Worksheets("Lists")
Set VisualWS = MainWB.Worksheets(4)
Set OverWS = MainWB.Worksheets(2)
Set DoubleWS = MainWB.Worksheets(3)
MonthName = UserForm1.ListOfMonths.Value
MainWB.Worksheets(1).Range("F2").Value = MonthName
lastcol = VisualWS.UsedRange.Columns.Count
LR = VisualWS.Cells(Rows.Count, "A").End(xlUp).Row

End Sub
Sub Analyze_1()

    Call initialize

    With OverWS

        LR_Over = .Cells(Rows.Count, "A").End(xlUp).Row
        .Range("M1").Value = "workdays"
        .Range("M2:M" & LR_Over).FormulaR1C1 = "=VLOOKUP(RC[-12],visual!R2C1:R" & LR & "C" & lastcol & "," & lastcol & ",FALSE)"

    End With
End Sub

The spaces in the formula were the problem 公式中的空格是问题所在

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM