I have a source workbook and a destination workbook. The source book has a range (D13:F293
) that contains data values, as well as blank cells. The destination book contains the same range and various cells contain formulas.
I want to import data from the source book to the destination book, but ONLY cells that contain a value. Furthermore, if the destination book/cell contains a formula, I want to KEEP the formula in the cell.
My options are:
- Scan the source for blank cells and only import cells with data.
- Scan the destination for formulas, and if a formulas exists, don't import data to that cell.
I don't know how to do this. I am very new to VBA and don't fully understand the syntax. I have tried 3 times with code that either replaces formulas with blank cells, or gives an error.
This code copies blank cells to destination book:
Sub TransferData()
If Workbooks.Count > 1 Then
Workbooks(2).Sheets("HELOC").Range("D13:F293").Copy
Workbooks(1).Sheets("HELOC").Range("D13:F293").PasteSpecial xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Workbooks(2).Close savechanges:=False
Else
MsgBox "The data hasn't been transferred.", vbExclamation, "Error"
End If
End Sub
This code also copies blank cells to destination book:
Sub TransferData()
If Workbooks.Count > 1 Then
For Each cl In ActiveSheet.UsedRange
If cl.HasFormula() = True Then
Workbooks(1).Sheets("HELOC").Range("D13:F293") = Workbooks(1).Sheets("HELOC").Range("D13:F293")
Else
Workbooks(1).Sheets("HELOC").Range("D13:F293").Value = Workbooks(2).Sheets("HELOC").Range("D13:F293").Value
End If
Next cl
Workbooks(2).Close savechanges:=False
Else
MsgBox "The data hasn’t been transferred.", vbExclamation, "Error"
End If
End Sub
This code (modified from here) results in:
Runtime error 91 Object variable or With block variable not set on line:
"If mySourceBook.Cells(i, 1).Value <> "" Then"
Sub TransferData()
Dim mySourceBook As Worksheet, myDestinationBook As Worksheet, myBook As Workbook
Set myBook = Excel.ActiveWorkbook
Set mySource = myBook.Sheets("HELOC")
Set myImportData = Excel.ActiveWorkbook.Sheets("HELOC")
Dim i As Integer, j As Integer 'Define a couple integer variables for counting
j = 13
For i = 13 To 293
If mySourceBook.Cells(i, 1).Value <> "" Then
myDestinationBook.Cells(j, 2).Value = mySourceBook.Cells(i, 1).Value
j = j + 1
End If
Next i 'This triggers the end of the loop and moves on to the next value of "i".
Workbooks(2).Close savechanges:=False
MsgBox "The data hasn’t been transferred.", vbExclamation, "Error"
End Sub
I appreciate any advice given. But please, explain it to me like I'm a child as I don't fully comprehend VBA.