I have some vba code to open excel files based on the filename-date (i.e. "test-09Sep2016.xlsm".
After the file is opened, it searches through the workbook and attempts to find what I'm looking for. Once it returns the results, it will close the workbook and loop through the folder to find the next file and so forth....
The issue is that the file size is massive and opening the file takes quite a while, i'm wondering if there is a way to do so without opening the actual file.
My current code is below:
Sub firstCoord()
Dim fpath As String, fname As String
Dim dateCount As Integer, strDate As Date
Dim i As Integer, j As Integer, k As Integer, lastRow As Integer, lastRow2 As Integer
Dim ws As Worksheet, allws As Worksheet
Dim seg As String
Dim strNum As String
Dim strRow As Integer
lastRow = Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp).Row
seg = Mid(ThisWorkbook.Name, 34, 1)
With Application.WorksheetFunction
For i = 2 To lastRow
fpath = "_______\"
strDate = Sheet1.Range("B" & i)
strNum = seg & Format(Mid(Sheet1.Range("A" & i), 4, 3), "000") & "000"
dateCount = 0
Do While Len(Dir(fpath & "_____-" & Format(strDate - dateCount, "ddmmmyyyy") & ".xlsx")) = 0 And dateCount < 35
dateCount = dateCount + 1
Loop
fname = "____-" & Format(strDate - dateCount, "ddmmmyyyy") & ".xlsx"
Workbooks.Open (fpath & fname)
For Each ws In Workbooks(fname).Worksheets
If ws.Name Like "*all*" Then
Set allws = Workbooks(fname).Worksheets(ws.Name)
ws.Activate
End If
Next ws
lastRow2 = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row
ThisWorkbook.Activate
k = 1
Do While (.CountIf(Sheet1.Range("C" & i & ":" & "E" & i), "") <> 0 Or Sheet1.Range("F" & i) = "") And k <= lastRow2
If Left(allws.Range("A" & k), 7) = strNum Then
Sheet1.Range("C" & i) = allws.Range("D" & k)
Sheet1.Range("D" & i) = allws.Range("C" & k)
Sheet1.Range("E" & i) = allws.Range("E" & k)
ElseIf k = lastRow2 And Sheet1.Range("C" & i) = "" Then
Sheet1.Range("F" & i) = "Not Found"
End If
k = k + 1
Loop
Workbooks(fname).Close
Next i
End With
End Sub
Any help would be greatly appreciated!!
Thanks
It is possible to retrieve data from Excel without opening the file using adodb, but you must (as far as I know) know at least the first column/row and last column of the dataset in the target file. You do not need to know the last row.
For example, this code calls two separate procedures, one that returns the value from a single cell and one that returns the value of the first cell in the defined range, from a closed workbook named GetDataInClosedWB:
Sub Main()
Call GetDataFromSingleCell("A1")
Call GetDataFromRangeBlock("A2", "D")
End Sub
Sub GetDataFromSingleCell(cell As String)
Dim CN As Object ' ADODB.Connection
Dim RS As Object ' ADODB.Recordset
Set CN = CreateObject("ADODB.Connection")
Set RS = CreateObject("ADODB.Recordset")
CN.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & CStr("C:\Users\USERNAME\Desktop\GetDataInA1.xlsx") & _
";" & "Extended Properties=""Excel 12.0;HDR=No;"";"
RS.Open "SELECT * FROM [Sheet1$" & cell & ":" & cell & "];", CN, 3, 1 'adOpenStatic, adLockReadOnly
MsgBox (RS.Fields(0).Value)
End Sub
Sub GetDataFromRangeBlock(firstCell As String, lastCol As String)
'firstCell is the upper leftmost cell in the target range
'lastCol is the column reference (e.g. A,B,C,D...) of the last column in the
'target dataset
Dim CN As Object ' ADODB.Connection
Dim RS As Object ' ADODB.Recordset
Set CN = CreateObject("ADODB.Connection")
Set RS = CreateObject("ADODB.Recordset")
CN.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & CStr("C:\Users\USERNAME\Desktop\GetDataInA1.xlsx") & _
";" & "Extended Properties=""Excel 12.0;HDR=No;"";"
RS.Open "SELECT * FROM [Sheet1$" & firstCell & ":" & lastCol & "];", CN, 3, 1 'adOpenStatic, adLockReadOnly
MsgBox (RS.Fields(0).Value)
End Sub
The GetDataInClosedWB file has the value Hello World! in A1 and values FirstHeader, SecondHeader, ThirdHeader, and FourthHeader in range A2:D2, respectively. The first procedure returns Hello World! in a message box, and the second return FirstHeader in a message box.
Once you've loaded the data into a Recordset you can iterate through it and perform your logic.
Note: if you prefer early binding, you'll need to enable a reference to a Microsoft ActiveX Data Objects Library.
Related
I need to get values from Sheet1 Column A (number of rows changes every day - can be more than 7,000) and Sheet2 Column B (also dynamic - changes every day), put those values from the columns into an array in STRING type (can be two arrays as long as I can use them in the query) and use the array in vba query WHERE ... IN ('array') to be run in MS-SQL server.
I've tried different ways to get the values into an array but have failed as many solutions offered need to use Array AS Variant when I need String type (to work in the query). One method that kind of worked was getting the values (comma separated) into one cell in another sheet and using that cell.value in the query. But that method is only good for total rows of 3000 or less. I've tried adding more - like cell2.value, cell3.value, but I would get errors (ex)if there were no values available for cell3.value. Please help.
Sub GetData()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim fld As ADODB.Field
Dim mssql As String
Dim row As Integer
Dim Col As Integer
Dim WB As ThisWorkbook
'============THIS IS THE PART I NEED HELP WITH ======================
Dim strArray() As String 'TRYING TO GET VALUES FROM COLUMN AS ARRAY
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.count).End(xlUp).row
ReDim strArray(1 To TotalRows)
For i = 1 To TotalRows
strArray(i) = Cells(i, 1).Value & "','" 'TRYING TO INCLUDE COMMAS BETWEEN VALUES
Next
'===========================================================================
Set WB = ThisWorkbook
Application.ScreenUpdating = False
Set oConn = New ADODB.Connection 'NEED TO CONNECT TO SQL SERVER TO RUN QUERY
Set rs = New ADODB.Recordset
mssql = "SELECT Order.ID, Order.OrderDate, Order.Account" _
& " FROM dbo.tbl_Order" _
& " WHERE Order.ID IN ('" & strArray() & "0'")" '<=== THIS IS WHERE I NEED TO INSERT STRING ARRAY
oConn.ConnectionString = "driver={SQL Server};" & _
"server=SERVER01;authenticateduser = TRUE;database=DATABASE01"
oConn.ConnectionTimeout = 30
oConn.Open
rs.Open mssql, oConn
If rs.EOF Then
MsgBox "No matching records found."
rs.Close
oConn.Close
Exit Sub
End If
' ===clear data in columns in worksheet as new values are copied over old ones
' ===this part is working fine
Worksheets("Sheet3").Range("A:P").ClearContents
' START WRITING DATA TO SHEET3
row = 5
Col = 1
For Each fld In rs.Fields
Sheet3.Cells(row, Col).Value = fld.Name
Col = Col + 1
Next
rs.MoveFirst
row = row + 1
Do While Not rs.EOF
Col = 1
For Each fld In rs.Fields
Sheet1.Cells(row, Col).Value = fld
Col = Col + 1
Next
row = row + 1
rs.MoveNext
Loop
rs.Close
oConn.Close
End Sub
You don't want to build an array but rather a string with the values you need. I stripped down your code to illustrate how this works:
Sub GetData()
Dim values As String
Dim mssql As String
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.Count).End(xlUp).row
For i = 1 To TotalRows
values = values & "'" & Cells(i, 1).Value & "',"
Next
values = Mid(values, 1, Len(values) - 1)
mssql = "SELECT Order.ID, Order.OrderDate, Order.Account " & _
"FROM dbo.tbl_Order " & _
"WHERE Order.ID IN (" & values & ")"
MsgBox mssql
End Sub
Get Zero-Based From Column
If you can use an array of strings (don't know SQL), for column A you could e.g. use:
Dim strArray() As String: strArray = getZeroBasedFromColumn(Range("A2"))
If you have to use a string then you will have to do:
Dim strArray As String
strArray = "'" & Join(getZeroBasedFromColumn(Range("A2")), "','") & "'"
and use strArray without the parentheses.
Qualify the first cell range (A2) appropriately e.g. WB.Worksheets("Sheet1").Range("A2").
Both solutions use the following function.
The Code
Function getZeroBasedFromColumn( _
FirstCell As Range) _
As Variant
Const ProcName As String = "getZeroBasedFromColumn"
On Error GoTo clearError
If Not FirstCell Is Nothing Then
Dim rg As Range
Set rg = FirstCell.Resize(FirstCell.Worksheet.Rows.Count - FirstCell.Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If Not rg Is Nothing Then
Set rg = FirstCell.Resize(rg.Row - FirstCell.Row + 1)
Dim rCount As Long: rCount = rg.Rows.Count
Dim Data As Variant
If rCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
Else
Data = rg.Value
End If
Dim arr() As String: ReDim arr(0 To rCount - 1)
Dim i As Long
For i = 1 To rCount
arr(i - 1) = CStr(Data(i, 1))
Next i
getZeroBasedFromColumn = arr
End If
End If
ProcExit:
Exit Function
clearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Function
Sub getZeroBasedFromColumnTEST()
Dim arr() As String: arr = getZeroBasedFromColumn(Range("A1"))
End Sub
An alternative (if you have the necessary database permissions) is to create a temporary table and use a JOIN in place of the WHERE IN().
Option Explicit
Sub GetData()
' get list of order numbers from Col A Sheet1 and COl B Sheet2
Dim wb As Workbook, wsOut As Worksheet
Dim rngA As Range, rngB As Range
Dim ar, ar1, ar2, iLastRow As Long, SQL As String
Dim i As Long, n As Long, id As String
Set wb = ThisWorkbook
Set wsOut = wb.Sheets("Sheet3")
' copy sheet1 Column A into array ar1
iLastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).row
Set rngA = Sheet1.Range("A1:A" & iLastRow)
If rngA.Rows.Count = 1 Then
ar1 = Array(0, rngA.Cells(1, 1).Value2)
Else
ar1 = Application.Transpose(rngA.Value2)
End If
'Debug.Print "A", LBound(ar1), UBound(ar1)
' copy sheet2 column B into array ar2
iLastRow = Sheet2.Cells(Rows.Count, "B").End(xlUp).row
Set rngB = Sheet2.Range("B1:B" & iLastRow)
If rngB.Rows.Count = 1 Then
ar2 = Array(0, rngB.Cells(1, 1).Value2)
Else
ar2 = Application.Transpose(rngB.Value2)
End If
'Debug.Print "B", LBound(ar2), UBound(ar2)
' connect to DB and create temporary table
Dim oConn As New ADODB.Connection
With oConn
.ConnectionString = "driver={SQL Server};" & _
"server=SERVER01;authenticateduser = TRUE;database=DATABASE01"
.ConnectionTimeout = 30
.Open
End With
oConn.Execute "CREATE TABLE #tmp (ID varchar(20) NOT NULL,PRIMARY KEY (ID ASC))"
' prepare insert query
SQL = "INSERT INTO #tmp (ID) VALUES (?)"
Dim cmd As New ADODB.Command
With cmd
.CommandType = adCmdText
.ActiveConnection = oConn
.CommandText = SQL
.Parameters.Append .CreateParameter("p1", adVarChar, adParamInput, 20)
End With
' insert array values into temp table
Dim t0 As Single: t0 = Timer
For Each ar In Array(ar1, ar2)
oConn.BeginTrans
For i = 1 To UBound(ar)
id = Trim(ar(i))
If Len(id) > 0 Then
cmd.Execute n, id
End If
Next
oConn.CommitTrans
'Debug.Print i - 1 & " Inserted"
Next
n = oConn.Execute("SELECT COUNT(*) FROM #tmp")(0)
'Debug.Print n & " records inserted into #tmp in " & Format(Timer - t0, "#.0 secs")
' select records using join as where filter
SQL = " SELECT Ord.ID, Ord.OrderDate, Ord.Account" _
& " FROM [tbl_Order] as Ord" _
& " JOIN #tmp ON Ord.ID = #tmp.ID"
' output result
Dim rs As New ADODB.Recordset
Set rs = oConn.Execute(SQL, n)
wsOut.Range("A:P").ClearContents
' header
Dim fld, cell As Range
Set cell = wsOut.Cells(5, 1)
For Each fld In rs.Fields
cell = fld.Name
Set cell = cell.Offset(0, 1)
Next
' data
wsOut.Cells(6, 1).CopyFromRecordset rs
oConn.Close
' end
n = wsOut.Cells(Rows.Count, 1).End(xlUp).row - 6
MsgBox n & " rows witten in " & Format(Timer - t0, "0.00 secs")
End Sub
I Have been working on the recent post that I have posted a while ago, but apparently, the condition in the code still does not succeed.
I want to copy the data from some Source Workbook to my currently opened workbook in which I work, but only under condition if the defined name in my current workbook matches the first 18 characters of the variables in column N:N of the Source workbook from where I want to copy the data from.
I have used the help of brainac, who helped me modify that condition - it starts after the line of the stars, however, it still does not work. Without having that condition to match defined name (in my current workbook) with variables in column N:N (in the SourceWorkbook), the code works fine - so I have a problem with constructing the condition.
I added the line saying: ActiveArray.Close, to have the Source Workbook closed at the end of the process, however, The only result it returns is opening of the Source Workbook and that's all. The match and copy are not executed at all and no error occurs. Any idea why it could be? I appreciate any response.
Sub Copy_Data()
Dim ActiveArray As Variant
Dim SourceWBpath As Variant
Dim i As Long
endRow = 1003
Const l_MyDefinedName As String = "MyDefinedName"
Const s_ColumnToMatch As String = "N:N" 'The column in the Source Workbook to be match with My defined name
Application.ScreenUpdating = False
Set ActiveArray = ActiveWorkbook
Set SourceWBpath= ThisWorkbook.Worksheets("Test").Range("E1") 'Cell with path to the Source Workbook
Set SourceWB = Workbooks.Open(SourceWBpath)
Set MyWorkbook = ThisWorkbook.Worksheets("Test")
'**************************Copy Workbook content to this sheet****************************************************
With SourceWB
Dim i As Long
endRow = 1003
For i = 2 To endRow
Dim rngFound As Range
On Error Resume Next
Set rngFound =SourceWB.Worksheets("Sheet1").Range(s_ColumnToMatch).Find(What:=l_MyDefinedName & "*", LookAt:=xlWhole)
Next i
On Error GoTo 0
If Not rngFound Is Nothing Then
rngFound.Parent.Range("A2:Y1900").Copy
ActiveArray.Sheets("Test").Range("A5").PasteSpecial xlPasteValues
Application.CutCopyMode = False
ActiveWorkbook.Close
End If
End With
End Sub
Perhaps something like this.
Sub GetData_Example1()
' It will copy the Header row also (the last two arguments are True)
' Change the last argument to False if you not want to copy the header row
GetData ThisWorkbook.Path & "\test.xls", "Sheet1", _
"A1:C5", Sheets("Sheet1").Range("A1"), True, True
End Sub
Option Explicit
Public Sub GetData(SourceFile As Variant, SourceSheet As String, _
SourceRange As String, TargetRange As Range, Header As Boolean, UseHeaderRow As Boolean)
' 30-Dec-2007, working in Excel 2000-2007
Dim rsCon As Object
Dim rsData As Object
Dim szConnect As String
Dim szSQL As String
Dim lCount As Long
' Create the connection string.
If Header = False Then
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=No"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=No"";"
End If
Else
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes"";"
End If
End If
If SourceSheet = "" Then
' workbook level name
szSQL = "SELECT * FROM " & SourceRange$ & ";"
Else
' worksheet level name or range
szSQL = "SELECT * FROM [" & SourceSheet$ & "$" & SourceRange$ & "];"
End If
On Error GoTo SomethingWrong
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect
rsData.Open szSQL, rsCon, 0, 1, 1
' Check to make sure we received data and copy the data
If Not rsData.EOF Then
If Header = False Then
TargetRange.Cells(1, 1).CopyFromRecordset rsData
Else
'Add the header cell in each column if the last argument is True
If UseHeaderRow Then
For lCount = 0 To rsData.Fields.Count - 1
TargetRange.Cells(1, 1 + lCount).Value = _
rsData.Fields(lCount).Name
Next lCount
TargetRange.Cells(2, 1).CopyFromRecordset rsData
Else
TargetRange.Cells(1, 1).CopyFromRecordset rsData
End If
End If
Else
MsgBox "No records returned from : " & SourceFile, vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
rsCon.Close
Set rsCon = Nothing
Exit Sub
SomethingWrong:
MsgBox "The file name, Sheet name or Range is invalid of : " & SourceFile, _
vbExclamation, "Error"
On Error GoTo 0
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function Array_Sort(ArrayList As Variant) As Variant
Dim aCnt As Integer, bCnt As Integer
Dim tempStr As String
For aCnt = LBound(ArrayList) To UBound(ArrayList) - 1
For bCnt = aCnt + 1 To UBound(ArrayList)
If ArrayList(aCnt) > ArrayList(bCnt) Then
tempStr = ArrayList(bCnt)
ArrayList(bCnt) = ArrayList(aCnt)
ArrayList(aCnt) = tempStr
End If
Next bCnt
Next aCnt
Array_Sort = ArrayList
End Function
Because of the high chances of the arrangement of columns being adjusted in my raw data, I want to store the column numbers in variables.
I think that my syntax Columns(Variable_name) is wrong, but can't figure what will work
I tried Columns("Variable_name") which didn't work too.
Set Cws = Worksheets.Add
Cws.Name = "Ready_For_Send"
Dim Region As Integer: Region = 1
Dim Sub_Region As Integer: Sub_Region = 2
Dim User_Status As Integer: User_Status = 5
Dim Count As Integer: Count = 15
With Cws
.Range(.Columns(Region) & "," & .Columns(Sub_Region) & "," & .Columns(User_Status) & "," & Columns(Count)).Delete
End With
You can use the following:
With Cws
.Range(Cells(1, Region).EntireColumn.Address & "," _
& Cells(1, Sub_Region).EntireColumn.Address & "," _
& Cells(1, User_Status).EntireColumn.Address & "," _
& Cells(1, Count).EntireColumn.Address).Delete
End With
You can use the Union to merge all your columns to one Range, and then delete it.
Try the code below:
Dim DelRng As Range
With Cws
' Set a new range from all the columns you want to delete
Set DelRng = Union(.Columns(Region), .Columns(Sub_Region), .Columns(User_Status), .Columns(Count))
DelRng.Delete
End With
May be something like this:
Option Explicit
Sub DeleteCols()
Dim wb As Workbook
Dim Csw As Worksheet
Dim Region As Long
Dim Sub_Region As Long
Dim User_Status As Long
Dim Count As Long
Dim Cws As Worksheet
Region = 1
Sub_Region = 2
User_Status = 5
Count = 15
Set wb = ThisWorkbook
Application.DisplayAlerts = False
On Error Resume Next
Set Cws = wb.Worksheets.Add
Cws.Name = "Ready_For_Send"
On Error GoTo 0
Application.DisplayAlerts = True
With Cws
.Range( _
ReturnName(Region) & ":" & ReturnName(Region) & "," & _
ReturnName(Sub_Region) & ":" & ReturnName(Sub_Region) & "," & _
ReturnName(User_Status) & ":" & ReturnName(User_Status) & "," & _
ReturnName(Count) & ":" & ReturnName(Count) _
).Delete Shift:=xlToLeft
End With
End Sub
Function ReturnName(ByVal num As Integer) As String
ReturnName = Split(Cells(, num).Address, "$")(1)
End Function
Some structure and Function from here: Delete multiple columns
I have included error handling in case sheet already exists. Also full declarations. I have also put declarations and assignments on different lines for ease of reading.
Im getting data from specific cells in closed workbooks but if the cell is empty it gets me empty cell. I need to improve get data function so if the cell from which i will be geting data is empty, then get data function return "/" or other character.
Thank you very much!
Sub Recurse()
Dim FSO As New FileSystemObject
Dim myFolder As Scripting.Folder, mySubFolder As Scripting.Folder
Dim myFile As File
Dim sPath$: sPath = "C:\Users\Marek\Desktop\skuska\"
Dim R$
R = Join(Application.Transpose(Sheets("Sheet2").UsedRange), "|")
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
DoEvents
If Not (InStr(1, R, myFile.Path) > 0) Then
GetData myFile, "Sheet1", "A1:A2", Sheets("Sheet1").Range(Sheets(1).Cells(Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1), Sheets(1).Cells(Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1)), True, False
GetData myFile, "Sheet1", "B1:B2", Sheets("Sheet1").Range(Sheets(1).Cells(Sheet1.Cells(Rows.Count, 2).End(xlUp).Row + 1, 2), Sheets(1).Cells(Sheet1.Cells(Rows.Count, 2).End(xlUp).Row + 1, 2)), True, False
GetData myFile, "Sheet1", "C1:C2", Sheets("Sheet1").Range(Sheets(1).Cells(Sheet1.Cells(Rows.Count, 3).End(xlUp).Row + 1, 3), Sheets(1).Cells(Sheet1.Cells(Rows.Count, 3).End(xlUp).Row + 1, 3)), True, False
Sheets("Sheet2").Cells(Sheets("Sheet2").UsedRange.Rows.Count + 1, 1).Value = myFile.Path
R = R & myFile.Path & "|"
End If
Next
Next
Set FSO = Nothing
Set myFolder = Nothing
Set mySubFolder = Nothing
Set myFile = Nothing
End Sub
Option Explicit
Public Sub GetData(SourceFile As Variant, SourceSheet As String, _
SourceRange As String, TargetRange As Range, Header As Boolean, UseHeaderRow As Boolean)
' 30-Dec-2007, working in Excel 2000-2007
Dim rsCon As Object
Dim rsData As Object
Dim szConnect As String
Dim szSQL As String
Dim lCount As Long
' Create the connection string.
If Header = False Then
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=No"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=No"";"
End If
Else
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes"";"
End If
End If
If SourceSheet = "" Then
' workbook level name
szSQL = "SELECT * FROM " & SourceRange$ & ";"
Else
' worksheet level name or range
szSQL = "SELECT * FROM [" & SourceSheet$ & "$" & SourceRange$ & "];"
End If
On Error GoTo SomethingWrong
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect
rsData.Open szSQL, rsCon, 0, 1, 1
' Check to make sure we received data and copy the data
If Not rsData.EOF Then
If Header = False Then
TargetRange.Cells(1, 1).CopyFromRecordset rsData
Else
'Add the header cell in each column if the last argument is True
If UseHeaderRow Then
For lCount = 0 To rsData.Fields.Count - 1
TargetRange.Cells(1, 1 + lCount).Value = _
rsData.Fields(lCount).Name
Next lCount
TargetRange.Cells(2, 1).CopyFromRecordset rsData
Else
TargetRange.Cells(1, 1).CopyFromRecordset rsData
End If
End If
Else
MsgBox "No records returned from : " & SourceFile, vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
rsCon.Close
Set rsCon = Nothing
Exit Sub
SomethingWrong:
MsgBox "The file name, Sheet name or Range is invalid of : " & SourceFile, _
vbExclamation, "Error"
On Error GoTo 0
End Sub
you'll need to loop through the data you've recieved cell by cell.. After the data has been pasted, use a loop to go through the target range (range of data on excel sheet) with a loop. so like:
for i = TargetRangeStartRow to numRowsInTargetRange
for j = TargetRangeStartCol to numColsInTargetRange
if Cells(i,j).formulaR1C1 = "" then
Cells(i,j).formulaR1C1 = "/"
end if
next
next
where obviously you'd need to use the first row in the target source, and the first column, and you'll need to get the number of rows and column in the target range as well. I say to use target range because that (Im assuming) is the range where the data is being pasted into Excel.
From Excel there isn't much of a way (I don't think?) to look at access and see beforehand if any of the data is missing. Regardless you'd still need to loop through the entire thing so it's just as well you do that after the data is pasted into Excel sheet.
I want to ask how to do this from vba code
Workbook 1 contain cell A, cell B, cell C
Workbook 2 contain Cell D
each cell contains number value
Cell D = (Cell A - Cell B) * Cell C
i want to calculate and just return value to cell D in workbook 2, Here my code snippet
Dim path As String
Dim workbookName As String
Dim worksheetName As String
Dim cella As String, cellb As String, cellc As String
Dim returnedValue1 As String, returnedValue2 As String, returnedValue3 As String
Dim Hasil1 As Long
path = "D:\"
workbookName = "Workbook1"
worksheetName = "Daily"
cella = "F7"
cellb = "E7"
cellc = "D7"
returnedValue1 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cella).Address(True, True, -4150)
returnedValue2 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellb).Address(True, True, -4150)
returnedValue3 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellc).Address(True, True, -4150)
Worksheets("Workbook2").Cells(D).Value = CLng(ExecuteExcel4Macro(returnedValue1) - ExecuteExcel4Macro(returnedValue2)) * ExecuteExcel4Macro(returnedValue3)
as far my code was good, but how to do it in one column, i have many cell beside just cell A. I want to calculate like this
Column D = (Column A - Column B ) * COlumn C
thanks for your answer..
Something like that (while row in column A is not empty, it populates your expression in column D):
Sub mmacro()
Dim path As String
Dim workbookName As String
Dim worksheetName As String
Dim cella As String, cellb As String, cellc As String, celld As String
Dim returnedValue1 As String, returnedValue2 As String, returnedValue3 As String
Dim Hasil1 As Long
Dim rownum As Integer
Dim A As Integer, B As Integer, C As Integer, D As Integer
path = "D:\tmp\"
workbookName = "Book2"
worksheetName = "Sheet1"
cella = "F"
cellb = "E"
cellc = "D"
celld = "A"
rownum = 3'Data starts in row 3 in my example
Do
returnedValue1 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cella & rownum).Address(True, True, -4150)
returnedValue2 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellb & rownum).Address(True, True, -4150)
returnedValue3 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellc & rownum).Address(True, True, -4150)
A = CInt(ExecuteExcel4Macro(returnedValue1))
B = CInt(ExecuteExcel4Macro(returnedValue2))
C = CInt(ExecuteExcel4Macro(returnedValue3))
D = (A - B) * C
Worksheets("Sheet1").Range(celld & rownum).Value = D
rownum = rownum + 1
Loop While Not D = 0
End Sub
This is just example. It is needed to be refined
Further to my comment here is a faster method which DOESN'T use looping. Use ACE.OLEDB to read the 3 columns into a temp sheet and then perform the calculation. Yes, ACE.OLEDB will open the other excel file but it doesn't open it like Excel does.
Note: The below code uses Early binding and please set a reference to the ActiveX Object Data XX.XX Library.
Option Explicit
Sub Sample()
Dim sConn As String
Dim rs As ADODB.Recordset
Dim mySQL As String, sPath As String
Dim wsI As Worksheet, wsO As Worksheet
Dim wsILRow As Long, i As Long
'~~> Change this to the relevant Excel File
sPath = "C:\MyFile.xlsx"
'~~> Change connection string if the above is not xlsx
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sPath & ";" & _
"Extended Properties=Excel 12.0"
'~~> Assuming that workbook 2 has sheet1 from where you want data
mySQL = "SELECT * FROM [Sheet1$A:C]"
Set rs = New ADODB.Recordset
rs.Open mySQL, sConn, adOpenUnspecified, adLockUnspecified
'~~> Create a temp sheeet to get the data from closed file
Set wsI = ThisWorkbook.Sheets.Add
'~~> Dump the data in the temp sheet
wsI.Range("A1").CopyFromRecordset rs
'~~> Close the recordset
rs.Close
sConn.Close
Set rs = Nothing
Set sConn = Nothing
'~~> Get last row from temp sheet
wsILRow = wsI.Range("A" & wsI.Rows.Count).End(xlUp).Row
'~~> This is where you want the output
Set wsO = ThisWorkbook.Sheets("Sheet1")
With wsO
'~~> Insert values in one go
.Range("D1:D" & wsILRow).Formula = "=(" & wsI.Name & "!A1 - " & _
wsI.Name & "!B1) * " & _
wsI.Name & "!C1"
'~~> Change formulas to values
.Range("D1:D" & wsILRow).Value = .Range("D1:D" & wsILRow).Value
End With
'~~> Delete tmep sheet
On Error Resume Next
Application.DisplayAlerts = False
wsI.Delete
Application.DisplayAlerts = False
On Error GoTo 0
End Sub