Copying data without opening workbook using Excel VBA - vba

I'm intending to copy data from one workbook to another through a macro. However, I'm using an Add-In my company has created, which prohibits more than one workbook to be open at once.
Application.ScreenUpdating = False
CurrentYear = Year(Date)
CurrentMonth = Month(Date)
StartDate = DateAdd("m", MonthOffset, Date)
MonthNo = Month(StartDate)
YearNo = Year(StartDate)
path2 = IIf(MonthNo >= 10, Dir("C:\path\filename " & YearNo & "-" & MonthNo & ".xlsx"), Dir("C:\path\filename " & YearNo & "-0" & MonthNo & ".xlsx"))
p2file = "C:\path"
Varrr = IIf(MonthNo >= 10, p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!", p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!")
i = 0
Do While Len(path2) > 0
Varrrcell = Cells(3,4+i).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Varrr = Varrr & Varrrcell
currentWb.Sheets("Blad1").Cells(27, 2 + i + 12 * (YearNo Mod 2015)).Formula= "=Varrr"
i = IIf(i > 12, 1, i + 1)
YearNo = IIf(i > 12, YearNo + 1, YearNo)
path2 = IIf(i >= 10, Dir("C:\path\filename " & YearNo & "-" & i & ".xlsx"), Dir("C:\path\filename" & YearNo & "-0" & i & ".xlsx"))
Varrr = IIf(i >= 10, p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!", p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!")
Loop
Application.ScreenUpdating = True
EDIT: I've recoded my work to reference to the workbook directly using formula. This solution actually returns the correct path, file and cell I want to copy so that works as intended. However, it returns "Varrr" in each cell. How can I make it return the value instead of the variable name?
EDIT2: I've also contatenated "='" before path2 & p2file & ".." when creating and updating Varrr, and simply saying that
currentWb.Sheets("Blad1").Cells(27, 2 + i + 12 * (YearNo Mod 2015)).Formula= Varrr
but this causes error 1004
EDIT3: I've also added a "closing" ' before the name of the sheet. It did not help.
EDIT4: I've also tried to omit the equal signs, and contenated Varrr = Varrr & Varrcell
and subsequentially put:
currentWb.Sheets("Blad1").Cells(27, 2 + i + 12 * (YearNo Mod 2015)).Formula = "=" & varrr
but it gives code 1004 in the same code snippet. "Application-defined or Object-defined error"
EDIT 5:
Trying to incorporate ExecuteExcel4Macro I've tried the following solution, where Dim ReturnedValue as String:
Varrr = "'" & p2file & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!'"
ReturnedValue = Varrr & Range("D3").Adress(True,True,-4150)
MsgBox ExecuteExcel4Macro(ReturnedValue)
where the MsgBox gives function error 1004. Here I have trimmed it down a bit to omit the "IIf" statement and the Do loop as I Believe these are redundant in the context.

Related

Invalid qualifier Error Message in vba code

This code is designed to detect the columns of start and finish of a shape which is used and displayed onto the caption of the shape itself. The following code is the problematic code:
Sub Take_Baseline()
Dim forcast_weeksStart() As String
Dim forcast_weeksEnd() As String
Dim forcastDate As String
Dim shp As Shape
Dim split_text() As String
'cycle through all the shapes in the worsheet and enter the forcast date for all the projects into their respective boxes
For Each shp In ActiveSheet.Shapes
'initialize forcast date by parsing
forcast_weeksStart = Split(shp.TopLeftCell.Column.Text, " ")
forcast_weeksEnd = Split(shp.BottomRightCell.Column.Text, " ")
forcastDate = forcast_weeksStart(1) & "-" & forcast_weeksEnd(1)
temp = shp.OLEFormat.Object.Object.Caption
If InStr(temp, "/-/") > 0 & InStr(temp, "In Prog") Then
split_text = Split(shp.OLEFormat.Object.Caption, " ")
For i = 0 To (i = 3)
shp.TextFrame.Characters.Caption = split_text(i) & vbNewLine
Next i
ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption = ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption & vbNewLine & ActiveSheet.Cells(4, AShape.TopLeftCell.Column).Text & " - " & ActiveSheet.Cells(4, AShape.BottomRightCell.Column).Text & vbNewLine & "dates: " & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & "/" & "actualDate"
' ElseIf InStr(temp, "/-/") > 0 & InStr(temp, "In Prog") = 0 Then
'split_text = Split(shp.OLEFormat.Object.Object.Caption, " ")
' For i = 0 To (i = 2)
' shp.OLEFormat.Object.Caption = split_text(i) & vbNewLine
' Next i
'ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption = ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption & vbNewLine & "In Prog" & vbNewLine & ActiveSheet.Cells(4, AShape.TopLeftCell.Column).Text & " - " & ActiveSheet.Cells(4, AShape.BottomRightCell.Column).Text & vbNewLine & "dates: " & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & "actualDate"
End If
Next shp
'For testing purposes
Sheet4.Range("A20").Value = forcast_weeksStart(1)
Sheet4.Range("A21").Value = forcast_weeksEnd(1) End Sub
The error is an
"invalid qualifier"
message which occurs on line
forcast_weeksStart = Split(shp.TopLeftCell.Column.Text, " ")
Right on the "column" word. I don't get why this is happening since the actual drop down menu has the column operation which i can select. I have tried everything from changing it to the OLEformat.Object.Caption etc etc. But nothing has worked. I am still relatively new to vba so any help will be appreciated. Thanks

Display formula in cell vba

I'd like to make the cell to appear as follows()
Desired outcome-- as I hover over cell
'E15'=(1+9.27%)*(1+C15)-1" and as I hover away the equation is evaluated
What I don't want E15 = (0.0000007)-1
I have two formulas that I was working on but I just can't seem to get it right.
I'd appreciate any help. Thanks in advance.
Range("E15").Formula = "=(" & 1 + "(" & Range("D15").Value & )"") * (" & 1 + "(" & Range("C15") & "))" - 1"
Range("E15").Formula = "=(" & 1 + "(" & Range("D15").Value & ")" & ") * (" & 1 + "(" & Range("C15") & ") & ") - 1"
Running:
Sub Macro1()
With Range("E15")
.ClearComments
.AddComment
.Comment.Visible = False
.Comment.Text Text:=Chr(39) & .Address(0, 0) & Chr(39) & " " & .Formula
End With
End Sub
produces:
NOTE:
It is equally easy to place the Comment in an adjacent cell.

VBA Error Message: Object Variable or With Block Variable not Set. Can't See It

Line 22 is throwing the error (Set wbPath2)
This code is supposed to loop through each worksheet in my workbook and, as it loops, open another workbook related to the current loop iteration, then sum a column, then put that SUM in my original workbook. I'm getting and object error 91. I've been scratching my head for a while. Anyone know why this error message appears?
Private Sub PopulateData_Click()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim lastDay As Long
lastDay = Day(WorksheetFunction.EoMonth(ComboBox1.Value & Year(Date), 0))
monthNumber = Month(DateValue("01-" & ComboBox1.Value & "-1900"))
Root = "C:\myDirectory\" & Year(Date) & "\" &
monthNumber & ". " & ComboBox1.Value & " " & Year(Date) & "\"
'TOTAL CARS PER WEEK
Dim wbPath2 As Object
sourceFile = monthNumber & ". " & ComboBox1.Value & " " & Year(Date)
sourceSheet = "\[" & ws.Name & " " & monthNumber & "." & lastDay & "." &
Format(Now(), "yy") & ".csv]"
For Each ws In ThisWorkbook.Sheets
If (ws.Name <> "Master") And (ws.Name <> "Combined") Then
Set wbPath2 = Workbooks.Open(Root & ws.Name & " " & monthNumber &
"." & lastDay & "." & Format(Now(), "yy") & ".csv")
With ws
.Cells(Application.WorksheetFunction.Match("Total cars per
week", Range("A:A"), 0), 18).Formula = "=SUM('" & Root &
sourceFile & sourceSheet & ws.Name & " " & monthNumber & "." &
lastDay & "." & Format(Now(), "yy") & "'!$H:$H)"
End With
wbPath2.Close
MsgBox wbPath2
End If
Next
Application.ScreenUpdating = True
End Sub
I had to Set the ws object to resolve run time 91 error. Look in the comments section for Mat's Mug's additional bug fixes.
Private Sub PopulateData_Click()
Application.ScreenUpdating = False
Dim ws As Worksheet
Set ws = ThisWorkbook.Activesheet
'...

Vb.net Excel Subtotals into variables

I've got Visual Basic Application that creates excel sheets based on the years, now in every excel sheet there will be subtotals of the given period that has been entered into the application. The total is being created by this:
oSheet.Range("F" & j + 1).Formula = "=SUBTOTAL(9,F" & summaryPosition & ":F" & j & ")"
oSheet.Range("G" & j + 1).Formula = "=SUBTOTAL(9,G" & summaryPosition & ":G" & j & ")"
oSheet.Range("H" & j + 1).Formula = "=SUBTOTAL(9,H" & summaryPosition & ":H" & j & ")"
oSheet.Range("I" & j + 1).Formula = "=SUBTOTAL(9,I" & summaryPosition & ":I" & j & ")"
oSheet.Range("J" & j + 1).Formula = "=SUBTOTAL(9,J" & summaryPosition & ":J" & j & ")"
Now i need to save these totals to a variable, but i have no idea how to get the totals into there. Anyone ever worked with Excel this way and knows how to solve this?
EDIT
I want to reference to the subtotal in the sheet, but i do not know how that works in Vb.net, any one an idea?
have you tried with
DIM var1 as oSheet.Range("F" & j + 1).Formula = "=SUBTOTAL(9,F" & summaryPosition & ":F" & j & ")"
it must get the result of that in var1

How to Implement Formula into Excel cells using VBA

I want to implement the following formula in to Excel cells
IF(OR(D12>0,C13=""),"",MAX(SUM($C$12:C13)-$D$9,0))
(once formula is applied I should get following result (formula implemented manually):
so i wrote simple macro as below , but unable to implement formula , formula retuns value as "true"
Sub adjustoldbills()
lastRow_sht4 = Sheet4.Range("A" & Rows.Count).End(xlUp).Row
Sheet4.Cells(12, 11) = ""
For i = 1 To lastRow_sht4 - 10
If Sheet4.Cells(11 + i, 1) <> "" Then
'=MAX(SUM($C$12:C15)-$D$9,0)
Sheet4.Cells(12, 4).Formula = "=MAX(SUM($C$12:C" & 12 & ")-$D$9,0)"
Sheet4.Cells(11 + i, 4).Formula = "=(if(or(D" & 11 + i > 0 & ",C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & "," & "MAX(SUM($C$12:C" & 12 & i & ")-$D$9,0)"
End If
Next i
End Sub
i am getting wrong result after implemented formula via vba macro as in this image:
how to implement formula and get value as expected.
When trying to convert long formulas to VBA try using a String variable to help you test it.
Dim FormulaStr As String
FormulaStr = "=IF(OR(D" & 11 + i & ">0,C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & _
Chr(34) & Chr(34) & ",MAX(SUM($C$12:C" & 12 + i & ")-$D$9,0))"
Debug.Print FormulaStr
Then, in the immediate window you will get:
=IF(OR(D12>0,C13=""),"",MAX(SUM($C$12:C13)-$D$9,0))
which is the formula you want to convert to VBA.
Now all you need to do is to add the line below:
Sheet4.Cells(11 + i, 4).Formula = FormulaStr
If you want to skip the String variable, you can just replace your line of
Sheet4.Cells(11 + i, 4).Formula = "=(if(or(D" & 11 + i > 0 & ",C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & "," & "MAX(SUM($C$12:C" & 12 & i & ")-$D$9,0)"
to:
Sheet4.Cells(11 + i, 4).Formula = "=IF(OR(D" & 11 + i & ">0,C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & ",MAX(SUM($C$12:C" & 12 + i & ")-$D$9,0))"
I'd go another way, with no loops and exploiting SpecialCells() method of Range object
Option Explicit
Sub adjustoldbills()
With Sheet4
.Range("D12").FormulaR1C1 = "=MAX(RC[-1]-R9C4,0)"
With .Range("A13", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
With .Offset(, 2).SpecialCells(xlCellTypeConstants)
.Offset(, 1).FormulaR1C1 = "=IF(R[-1]C>0,"""",MAX(SUM(R12C[-1]:RC[-1])-R9C4,0))"
With .Areas(.Areas.Count)
.Offset(, 1).Cells(.Rows.Count).Offset(1).FormulaR1C1 = "=IF(R[-1]C>0,"""",MAX(SUM(R12C[-1]:RC[-1])-R9C4,0))"
End With
End With
End With
End With
End Sub