简体   繁体   中英

VBA excel runtime error 13 type mismatch

i am new to vba and I cant seem fix this error. Getting a type mismatch on the line. If NameColumn.Value = "CR" Then

I feel like I'm close but cant see the problem. Posting full code hopefully someone will see my error! Thanks for the help

    Application.ScreenUpdating = False

Sheet2.Range("A1:H9999").ClearContents

Dim vFileName
Dim MyWorkbook As Workbook
Dim NameColumn As Range
Dim value1 As Range
Dim value2 As Range
Dim value3 As Integer


vFileName = Application.GetOpenFilename("Text Files (*.txt),*.txt")


Workbooks.OpenText Filename:=vFileName, _
    Origin:=437, _
    StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), Array(8, _
    1), Array(15, 1), Array(51, 1), Array(57, 1), Array(75, 1), Array(88, 1), Array(112, 1), _
    Array(126, 1)), TrailingMinusNumbers:=True
Set MyWorkbook = ActiveWorkbook
Columns("A:I").Select
Selection.Copy
Windows("Book1.xlsm").Activate
Columns("A:A").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
MyWorkbook.Activate
Application.DisplayAlerts = False
ActiveWindow.Close
Set value1 = ActiveSheet.Range("K113:K249")
Set value2 = ActiveSheet.Range("H113:H249")
Set NameColumn = ActiveSheet.Range("I113:I249")
If NameColumn.Value = "CR" Then
    value1.Value = value1.Value * -1
    ElseIf value2.Value = 0 Or value2.Value = "" Then
    value1.Value = ""
    Else: value1.Value = value1.Value
End If

Range("L1").Formula = "=Sum(H113:H249)"


MyWorkbook.Range("L1").Value = value3

MsgBox "Yes. Offset to zero" & value3

Application.ScreenUpdating = True
End Sub        

You are trying to evaluate the value of a range of cells, rather than a single cell. Try -

Set NameColumn = ActiveSheet.Range("I113:I249")
For each c in NameColumn
 If c.Value = "CR" Then
    value1.Value = value1.Value * -1
    ElseIf value2.Value = 0 Or value2.Value = "" Then
    value1.Value = ""
    Else: value1.Value = value1.Value
 End If
Next

You'll probably need to figure out what the stuff after the if should be doing for each c .


I think since value1 is column k and value2 is column H, you can address them as offsets to column I -

Set NameColumn = ActiveSheet.Range("I113:I249")
For each c in NameColumn
 If c.Value = "CR" Then
    c.offset(,2) = c.offset(,2) * -1
    ElseIf c.offset(,-1) = 0 Or c.offset(,-1) = "" Then
    c.offset(,2) = ""
    Else: c.offset(,2) = c.offset(,2)
 End If
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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