printing gridlines in excel through interop - excel

I'm trying to export DataGridView items to Excel file and everything perfect, but I want the gridlines appear when the client want to print the sheet, I can do this from inside excel as shown here.
but how can I do this from the vb.net code ??
and I have a problem that : I cant make the text Alignment center I tried this code:
wSheet.Range("a2", "z1000").HorizontalAlignment = excel.XlVAlign.xlVAlignCenter
but it show this error: Public member 'XlVAlign' on type 'ApplicationClass' not found.
Is there a different way to make all columns Alignment center.
this Is my code :
If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
Exit Sub
End If
'Creating dataset to export
Dim dset As New DataSet
'add table to dataset
dset.Tables.Add()
'add column to that table
For i As Integer = 0 To DataGridView1.ColumnCount - 1
If DataGridView1.Columns(i).Visible = True Then
dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
End If
Next
Dim celltext As String
Dim count As Integer = -1
'add rows to the table
Dim dr1 As DataRow
For i As Integer = 0 To DataGridView1.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Columns(j).Visible = True Then
count = count + 1
dr1(count) = DataGridView1.Rows(i).Cells(j).Value
End If
Next
count = -1
dset.Tables(0).Rows.Add(dr1)
Next
Dim excel As New Excel.Application
Dim wBook As Excel.Workbook
Dim wSheet As Excel.Worksheet
wBook = excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dset.Tables(0)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
' for the header
wSheet.Rows(1).Font.Name = "Droid Arabic Kufi"
wSheet.Rows(1).Font.size = 11
wSheet.Rows(1).Font.Bold = True
wSheet.Rows(1).HorizontalAlignment = HorizontalAlignment.Right
Dim mycol As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#20b2aa")
wSheet.Rows(1).Font.color = mycol
' for all the sheet without header
wSheet.Range("a2", "z1000").Font.Name = "Droid Arabic Kufi"
wSheet.Range("a2", "z1000").Font.Size = 10
wSheet.Range("a2", "z1000").HorizontalAlignment = excel.XlVAlign.xlVAlignCenter
wSheet.Range("A1:X1").EntireColumn.AutoFit()
wSheet.Range("A1:X1").EntireRow.AutoFit()
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Excel Workbook|*.xls|Excel Workbook 2011|*.xlsx"
saveFileDialog1.Title = "Save Excel File"
saveFileDialog1.FileName = "Export " & Now.ToShortDateString & ".xlsx"
saveFileDialog1.ShowDialog()
saveFileDialog1.InitialDirectory = "C:/"
If saveFileDialog1.FileName <> "" Then
Dim fs As System.IO.FileStream = CType(saveFileDialog1.OpenFile(), System.IO.FileStream)
fs.Close()
End If
Dim strFileName As String = saveFileDialog1.FileName
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
Exit Sub
End Try
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
excel.Workbooks.Open(strFileName)
excel.Visible = True
Exit Sub
errorhandler:
MsgBox(Err.Description)
End Sub
And Is there a way to make rows In different color like row 1 background color blue Row 2 background color white, row 2 background color blue Row 4 background color ...etc
Note :
what is the default :
what I want :

First change the following code:
wSheet.Range("a2", "z1000").HorizontalAlignment = excel.XlVAlign.xlVAlignCenter
TO
wSheet.Range("a2", "z1000").HorizontalAlignment = excel.XlHAlign.xlHAlignCenter
Cell font color , size
Dim formatRange As Excel.Range
formatRange = xlWorkSheet.Range("b1", "b1")
formatRange.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
formatRange.Font.Size = 10
xlWorkSheet.Cells(1, 2) = "Red"
Add border to a specific cell
Dim formatRange As Excel.Range = xlWorkSheet.UsedRange
Dim cell As Excel.Range = formatRange.Cells(3, 3)
Dim border As Excel.Borders = cell.Borders
border.LineStyle = Excel.XlLineStyle.xlContinuous
border.Weight = 2.0
Border around multiple cells in excel
Dim formatRange As Excel.Range = wSheet.UsedRange
Dim cell As Excel.Range = wSheet.Range("a1", "e" & DataGridView1.RowCount & "")
Dim border As Excel.Borders = cell.Borders
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
border.Weight = 2.0
Read more in this Article

Thank to H.Fadlallah for helping me
This the answer:
make Gridlines to the excel sheet :
Dim formatRange As Excel.Range = wSheet.UsedRange
Dim cell As Excel.Range = wSheet.Range("a1", "j" & DataGridView1.RowCount + 1 & "")
Dim border As Excel.Borders = cell.Borders
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
border.Weight = 1.0
And this code to make Alignment center :
wSheet.Range("a2", "z1000").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
And this is the All Code To export DataGridView To Excel:
Button code :
Private Sub To_Excel_picbox_but_Click(sender As Object, e As EventArgs) Handles To_Excel_picbox_but.Click
Try
Dim day As Integer = Date.Today.Day
Dim month As Integer = Date.Today.Month
Dim year As Integer = Date.Today.Year
SaveFileDialog1.Filter = "Excel File|*.xlsx"
SaveFileDialog1.Title = "Save an Excel File"
SaveFileDialog1.FileName = " الحوالات المرسلة" & day & "-" & month & "-" & year & ".xlsx"
SaveFileDialog1.InitialDirectory = "C:/"
Application.EnableVisualStyles()
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
If SaveFileDialog1.FileName <> "" Then
BackgroundWorker2.RunWorkerAsync()
Dim fs As System.IO.FileStream = CType(SaveFileDialog1.OpenFile(), System.IO.FileStream)
fs.Close()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
BackGroundWorker do work code:
Private Sub BackgroundWorker2_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker2.DoWork
ExporttoExcel(DataGridView1)
End Sub
Export Data To Excel Code:
Sub ExporttoExcel(ByVal DataGridView1 As DataGridView)
'verfying the datagridview having data or not
If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
Exit Sub
End If
'Creating dataset to export
Dim dset As New DataSet
'add table to dataset
dset.Tables.Add()
'add column to that table
For i As Integer = 0 To DataGridView1.ColumnCount - 1
If DataGridView1.Columns(i).Visible = True Then
dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
End If
Next
Dim celltext As String
Dim count As Integer = -1
'add rows to the table
Dim dr1 As DataRow
For i As Integer = 0 To DataGridView1.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Columns(j).Visible = True Then
count = count + 1
dr1(count) = DataGridView1.Rows(i).Cells(j).Value
End If
Next
count = -1
dset.Tables(0).Rows.Add(dr1)
Next
Dim excel As New Excel.Application
Dim wBook As Excel.Workbook
Dim wSheet As Excel.Worksheet
wBook = excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dset.Tables(0)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
'calculate the sum for "المبلغ" from the datagridview
Dim Result As Double
For i As Integer = 0 To DataGridView1.RowCount - 1
Result += DataGridView1.Rows(i).Cells(0).Value
'Change the number 2 to your column index number (The first column has a 0 index column)
'In this example the column index of Price is 2
Next
'add the sum to sheet
wSheet.Cells(DataGridView1.RowCount + 2, 1) = Result
wSheet.Cells(DataGridView1.RowCount + 2, 2) = "المجموع"
' for the header
wSheet.Rows(1).Font.Name = "Droid Arabic Kufi"
wSheet.Rows(1).Font.size = 11
wSheet.Rows(1).Font.Bold = True
wSheet.Rows(1).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
Dim mycol As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#20b2aa")
wSheet.Rows(1).Font.color = mycol
' for all the sheet without header
wSheet.Range("a2", "z1000").Font.Name = "Droid Arabic Kufi"
wSheet.Range("a2", "z1000").Font.Size = 10
' make the sheet Alignment center
wSheet.Range("a2", "z1000").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
wSheet.Range("A1:X1").EntireColumn.AutoFit()
wSheet.Range("A1:X1").EntireRow.AutoFit()
wSheet.Columns("J").ColumnWidth = 28
'make the first column "المبلغ" format is money
wSheet.Columns("A").NumberFormat = "#,##0_);[Red](#,##0)"
' this add Grid line to all rows and columns
Dim formatRange As Excel.Range = wSheet.UsedRange
Dim cell As Excel.Range = wSheet.Range("a1", "j" & DataGridView1.RowCount + 1 & "")
Dim border As Excel.Borders = cell.Borders
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
border.Weight = 1.0
' this add header and footer when printing the sheet
wSheet.PageSetup.CenterHeader = "&""Droid Arabic Kufi,Bold""&14الحوالات الصادرة"
wSheet.PageSetup.RightFooter = DateTime.Now
wSheet.PageSetup.LeftFooter = "Page &P of &N"
'make the print page horizontal
wSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape
'make all columns fit in one page
wSheet.PageSetup.Zoom = False
wSheet.PageSetup.FitToPagesWide = 1
wSheet.PageSetup.FitToPagesTall = False
Dim strFileName As String = saveFileDialog1.FileName
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
Exit Sub
End Try
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
excel.Workbooks.Open(strFileName)
excel.Visible = True
Exit Sub
errorhandler:
MsgBox(Err.Description)
End Sub

My answer to your question is really simple with:
xlWorksheet.PageSetup.PrintGridLines = True

Related

Find the number of duplicates (Column for particular record with each serial number)

I need the expert help in VBA Excel code. I need to find the number of duplicate record (AlertToString) for particular device serial number from the source sheet serial number and paste it to the other newly created output sheet by using VBA Macro.
Example (Source sheet):
Expected (Output Sheet with repeat Alert count) :
Source code as below :
Sub Alert700Count()
Dim AlertSource_Sh As Worksheet
Dim AlertOutput_Sh As Worksheet
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("AlertOutput").Delete
Sheets.Add.Name = "AlertOutput"
Application.DisplayAlerts = True
Set AlertSource_Sh = ThisWorkbook.Sheets("SourceSheet")
Set AlertOutput_Sh = ThisWorkbook.Sheets("AlertOutput")
AlertOutput_Sh.Cells(1, 1) = "Serial No"
AlertOutput_Sh.Cells(1, 2) = "A92"
AlertOutput_Sh.Cells(1, 3) = "A95"
AlertOutput_Sh.Cells(1, 4) = "A98"
For Each sh In ActiveWorkbook.Worksheets
With sh.Range("A1:D1")
.Font.Bold = True
.WrapText = True
.CellWidth = 35
.Selection.Font.ColorIndex = 49
.Weight = xlMedium
.LineStyle = xlDash
End With
Next sh
AlertOutput_Sh.Range("A1:D1").Borders.Color = RGB(10, 201, 88)
AlertOutput_Sh.Columns("A:D").ColumnWidth = 12
AlertOutput_Sh.Range("A1:D1").Font.Color = rgbBlueViolet
AlertOutput_Sh.Range("A1:D1").Interior.Color = vbYellow
AlertOutput_Sh.Range("A1:D1").HorizontalAlignment = xlCenter
AlertOutput_Sh.Range("A1:D1").VerticalAlignment = xlTop
' Search the duplicate record and paste in output sheet
Dim A92Count As Long
A92Count = Application.CountIf(AlertSource_Sh.Range("D:D"), "A92")
AlertOutput_Sh.Cells(2, 2) = A92Count
Dim A95Count As Long
A95Count = Application.CountIf(AlertSource_Sh.Range("D:D"), "A95")
AlertOutput_Sh.Cells(2, 3) = A92Count
Dim A98Count As Long
A98Count = Application.CountIf(AlertSource_Sh.Range("D:D"), "A98")
AlertOutput_Sh.Cells(2, 4) = A98Count
End Sub
Current Output :
Use Dictionaries to build lists of unique values and an array to hold the counts.
Option Explicit
Sub Alert700Count()
Dim wsData As Worksheet, wsOut As Worksheet
Dim dictSerNo As Object, dictAlert As Object
Dim arData, arOut, k, rngOut As Range
Dim lastrow As Long, i As Long
Dim serNo As String, alert As String
Dim r As Long, c As Long, t0 As Single: t0 = Timer
Set dictSerNo = CreateObject("Scripting.Dictionary")
Set dictAlert = CreateObject("Scripting.Dictionary")
On Error Resume Next
Application.DisplayAlerts = False
Sheets("AlertOutput").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Sheets.Add.Name = "AlertOutput"
Set wsOut = Sheets("AlertOutput")
Set wsData = Sheets("SourceSheet")
r = 1: c = 1
With wsData
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
arData = .Range("A1:D" & lastrow).Value2
' get unique serno and alert
For i = 2 To lastrow
serNo = arData(i, 1)
alert = arData(i, 4)
If dictSerNo.exists(serNo) Then
ElseIf Len(serNo) > 0 Then
r = r + 1
dictSerNo.Add serNo, r
End If
If dictAlert.exists(alert) Then
ElseIf Len(alert) > 0 Then
c = c + 1
dictAlert.Add alert, c
End If
Next
' rescan for counts
ReDim arOut(1 To r, 1 To c)
For i = 2 To lastrow
r = dictSerNo(CStr(arData(i, 1)))
c = dictAlert(CStr(arData(i, 4)))
arOut(r, c) = arOut(r, c) + 1
Next
End With
' add headers
arOut(1, 1) = "Serial No"
' sernos and alerts
For Each k In dictSerNo
arOut(dictSerNo(k), 1) = k
Next
For Each k In dictAlert
arOut(1, dictAlert(k)) = k
Next
' output counts
With wsOut
Set rngOut = .Range("A1").Resize(UBound(arOut), UBound(arOut, 2))
rngOut.Value2 = arOut
rngOut.Replace "", 0
.ListObjects.Add(xlSrcRange, rngOut, , xlYes).Name = "Table1"
.Range("A1").AutoFilter
.Range("A1").Select
End With
MsgBox "Done", vbInformation, Format(Timer - t0, "0.0 secs")
End Sub

doesnt run for loop

Every part of this Code is executed but the part inside of the for loop on the top
I tried to rewrite this part of the code because one time it helped in vba but just this part would want to run
Do While Not IsEmpty(Sheets("Overview").Cells(ovrow, ovcol))
For row = 2 To length
If Sheets(wsname).Cells(row, column) = Sheets("Overview").Cells(ovrow, ovcol) Then
counter = counter + 1
End If
Next row
Sheets("Overview").Cells(ovrow, ovcol).Offset(0, 1).value = counter
counter = 0
If Sheets("Overview").Cells(ovrow, ovcol).Offset(1, 0).value = "" Then
ovrow = 2
ovcol = ovcol + 2
column = column + 1
Else
ovrow = ovrow + 1
End If
Cells(ovrow, ovcol).Select
Loop
It should just count to the variable counter higher but nothing happens. I put some messageboxes inside my code so i can see where the code is in the excel cells but the counter variable stays at 0
This is the full code
Private Sub RefreshBtn_Click()
Dim source As String
Dim sourcerow As Integer
Dim sourcecolumn As Integer
Dim target As String
Dim targetrow As Integer
Dim targetcolumn As Integer
Dim i As Integer
sourcerow = 2
sourcecolumn = 1
source = Sheets("Devices").Cells(sourcerow, sourcecolumn).value
targetrow = 2
targetcolumn = 3
For i = 1 To 6
Do While Not IsEmpty(Cells(targetrow, targetcolumn))
Cells(targetrow, targetcolumn).value = ""
targetrow = targetrow + 1
Loop
targetrow = 2
targetcolumn = targetcolumn + 2
Next i
targetrow = 2
targetcolumn = 3
For i = 1 To 6
Do While Not IsEmpty(Sheets("Devices").Cells(sourcerow, sourcecolumn))
source = Sheets("Devices").Cells(sourcerow, sourcecolumn).value
Sheets("Overview").Cells(targetrow, targetcolumn).value = source
sourcerow = sourcerow + 1
targetrow = targetrow + 1
Loop
sourcecolumn = sourcecolumn + 1
sourcerow = 2
targetrow = 2
targetcolumn = targetcolumn + 2
Next i
Dim length As Integer
Dim row As Integer
Dim column As Integer
Dim yearnow As String
Dim monthnow As String
Dim daynow As String
Dim wsname As String
Dim readdate As String
Dim ws As Worksheet
daynow = Day(Now())
If daynow > 20 Then
monthnow = month(Now()) + 1
If monthnow = "Januar" Then
yearnow = Year(Now()) + 1
End If
Else
monthnow = month(Now())
yearnow = Year(Now())
End If
wsname = yearnow + MonthName(monthnow)
For Each ws In ActiveWorkbook.Sheets
If ws.Name = wsname Then
exist = True
End If
Next ws
Sheets("Overview").Cells(2, 2).value = wsname
row = 2
column = 4
length = 0
If exist = True Then
Do While Not IsEmpty(Sheets(wsname).Cells(row, column))
row = row + 1
length = length + 1
Loop
Else
MsgBox "Für den aktuellen Monat sind keine Offenen Bestellung vorhanden"
End If
Dim counter As Integer
counter = 0
Dim ovrow As Integer
Dim ovcol As Integer
ovrow = 2
ovcol = 3
Do While Not IsEmpty(Sheets("Overview").Cells(ovrow, ovcol))
For row = 2 To length
If Sheets("Overview").Cells(ovrow, ovcol).value = Sheets(wsname).Cells(row, column).value Then
counter = counter + 1
MsgBox "hallo"
End If
Next row
Sheets("Overview").Cells(ovrow, ovcol).Offset(0, 1).value = counter
counter = 0
If Sheets("Overview").Cells(ovrow, ovcol).Offset(1, 0).value = "" Then
ovrow = 2
ovcol = ovcol + 2
column = column + 1
Else
ovrow = ovrow + 1
End If
Cells(ovrow, ovcol).Select
Loop
End Sub

Excel vba not displaying results

I'm a beginner in VBA and so would appreciate some help. I'm trying to build a directory to display results based on user selection of 'category' and 'subcategory'. When I run the script, there is no error message but I don't see any results displayed. Is there anything wrong with my code?
Sub Button5_Click()
'''Function to search data set
Dim wkbk As Workbook
Dim row_data As Range
Dim results_ws As Worksheet, data_ws As Worksheet
Dim n_row As Integer '''counter for row number
Dim main_ws As Worksheet
Dim category As String, subcategory As String
Set wkbk = ThisWorkbook
Set results_ws = wkbk.Sheets("Demo_Results")
Set data_ws = wkbk.Sheets("Demo_Data")
Set main_ws = ThisWorkbook.Sheets("Demo_Main")
'''Clear the results worksheet
results_ws.Cells.ClearContents
results_ws.Hyperlinks.Delete
results_ws.Cells.Font.Underline = False
results_ws.Columns("B:E").Font.Color = RGB(0, 0, 0)
category = main_ws.Cells(13, "F").Value
subcategory = main_ws.Cells(15, "F").Value
result_count = 0
final_data_row = data_ws.Range("A1000").End(xlUp).Row
For n_row = 2 To final_data_row:
If data_ws.Cells(n_row, "A") = category And data_ws.Cells(n_row, "B") = subcategory Then
With data_ws
Set row_data = data_ws.Range(data_ws.Cells(n, 1), data_ws.Cells(n, 7))
result_count = result_count + 1
results_ws.Cells(Rows.Count, "E").End(xlUp).Offset(2, -3).Value = Str(result_count) + ".)"
results_ws.Cells(Rows.Count, "E").End(xlUp).Offset(2, -2).Value = row_data.Cells(1, 3).Value
'''Enter state
results_ws.Cells(Rows.Count, "C").End(xlUp).Offset(1, 1).Value = "State:"
results_ws.Cells(Rows.Count, "D").End(xlUp).Offset(0, 1).Value = row_data.Cells(1, 4).Value
End With
End If
Next n_row
'''Format table
Sheets("Demo_Results").Select
Call ResetFormatting
ActiveWindow.ScrollRow = 1
End Sub
Function ResetFormatting():
'''Resent font style and size for results column
Dim wsheet As Worksheet
Set wsheet = ThisWorkbook.Sheets("Demo_Results")
wsheet.Cells.Font.Name = "Verdana"
wsheet.Cells.Font.Size = 11
End Function

Need a way to make the loop faster in Excel VBA

I work for a construction company. I have been writing a macro for the inventory department which can retrieve the latest date on which a particular type of material was supplied to a specific Flat No. at site.
The code which I have is doing the job but it's taking very long to compute all the results. Can anyone tell me how to make this go even faster.
Following is the code:
Sub FillTopSheet()
'Designing a loop to move through the fill data on Top Sheet
Application.ScreenUpdating = False
'Declaring variables for counts
Dim Flat_Row_Num As Long
Dim Tower_Col_Num As Long
Dim InventoryWs As Worksheet
'Debug.Print Application.Workbooks("The Crest DLF Project-In-Out Inventory Data.xlsx").Worksheets("Material-Out").Name
Set InventoryWs = Application.Workbooks("The Crest DLF Project-In-Out Inventory Data.xlsx").Worksheets("Material-Out")
Dim Lookup_Start_Row As Long
Dim Lookup_End_Row As Long
'Lookup_Start_Row = 4
'
'Select Case Application.ThisWorkbook.ActiveSheet.Name
' Case "Kitchen Carcass"
' Do Until InventoryWs.Cells(Lookup_Start_Row, 2).Value = "Kitchen Carcass"
' Lookup_Start_Row = Lookup_Start_Row + 1
' Loop
'
' Lookup_End_Row = Lookup_Start_Row
'
' Do While InventoryWs.Cells(Lookup_End_Row, 2).Value = "Kitchen Carcass"
' Lookup_End_Row = Lookup_End_Row + 1
'
' Loop
'
' Lookup_End_Row = Lookup_End_Row - 1
'
'End Select
Debug.Print Lookup_Start_Row
Debug.Print Lookup_End_Row
Lookup_Start_Row = 6162
Lookup_End_Row = 14754
Flat_Row_Num = 5
Tower_Col_Num = 5
Do Until Tower_Col_Num > 13
Do Until Flat_Row_Num > 154
If Application.ThisWorkbook.ActiveSheet.Cells(Flat_Row_Num, Tower_Col_Num - 1).Value <> "" Then
Do Until Lookup_Start_Row = Lookup_End_Row
If Application.ThisWorkbook.ActiveSheet.Cells(Flat_Row_Num, Tower_Col_Num - 1).Value = _
InventoryWs.Cells(Lookup_Start_Row, 8).Value Then
Application.ThisWorkbook.ActiveSheet.Cells(Flat_Row_Num, Tower_Col_Num).Value = _
InventoryWs.Cells(Lookup_Start_Row, 6).Value
GoTo RowReset
Else
Application.ThisWorkbook.ActiveSheet.Cells(Flat_Row_Num, Tower_Col_Num).Value = "NA"
End If
Lookup_Start_Row = Lookup_Start_Row + 1
Loop
Lookup_Start_Row = 6162
RowReset:
Lookup_Start_Row = 6162
End If
Flat_Row_Num = Flat_Row_Num + 1
Loop
Flat_Row_Num = 5
Tower_Col_Num = Tower_Col_Num + 2
Loop
Application.ScreenUpdating = True
End Sub
Could be something like this but indexes (i,j,k) might be mixed up.
Would be much easier if you could post your input and desired output (eg some screenshot)
Sub FillTopSheet()
'Declaring variables for counts
Dim Flat_Row_Num As Long
Dim Tower_Col_Num As Long
Dim InventoryWs As Worksheet, Ws As Worksheet
Dim ArrLookUp() As Variant, ArrData() As Variant
Dim Lookup_Start_Row As Long, Lookup_End_Row As Long, i As Long, j As Long, k As Long
Dim FlatNo As String
'Designing a loop to move through the fill data on Top Sheet
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Debug.Print Application.Workbooks("The Crest DLF Project-In-Out Inventory Data.xlsx").Worksheets("Material-Out").Name
Set InventoryWs = Application.Workbooks("The Crest DLF Project-In-Out Inventory Data.xlsx").Worksheets("Material-Out")
Debug.Print Lookup_Start_Row
Debug.Print Lookup_End_Row
Lookup_Start_Row = 6162
Lookup_End_Row = 14754
Flat_Row_Num = 5
Tower_Col_Num = 2 'Start in Tower A "Flats No. column
With InventoryWs
ArrLookUp = .Range(.Cells(Lookup_Start_Row, 6), .Cells(Lookup_End_Row, 8))
End With
With Ws
ArrData = .Range(.Cells(Flat_Row_Num, Tower_Col_Num), .Cells(154, 13))
End With
For i = LBound(ArrData, 2) To UBound(ArrData, 2) Step 2
For j = LBound(ArrData) To UBound(ArrData)
'loop through "towers" Array
FlatNo = ArrData(j, i) 'take one flat no
If FlatNo <> "" Then
For k = LBound(ArrLookUp) To UBound(ArrLookUp)
'look for this flat no in other array
If FlatNo = ArrLookUp(k, 3) Then
'first match = take Date from other array
'dates sorted descending
ArrData(j, i + 1) = ArrLookUp(k, 1)
'found what was looking for, get out of loop
Exit For
End If
Next k
End If
Next j
Next i
With Ws
'range must be same as when you set the array earlier. But if that range contains some formulas they'll be overwriten with values
'in that case you can loop through array and take out only dates
.Range(.Cells(Flat_Row_Num, Tower_Col_Num), .Cells(154, 13)) = ArrData
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Edit
This still might need some adjustment to fit in your ranges
Check ranges in ArrLookUp = .Range(.Cells(Lookup_Start_Row, 6), .Cells(Lookup_End_Row, 8)) and ArrLookUp = .Range(.Cells(Lookup_Start_Row, 6), .Cells(Lookup_End_Row, 8))
It takes "Towers" and looks for "Flats No." in other sheet. At first match date is taken from other sheet.

Excel UDF #VALUE! Error

The below Code Counts the number of unique names is a specific column after inputting the data into an array. It works perfectly when running in the the immediate window. But when using as a UDF it throws #Value Error. I am taking all the data into an array and checking the array and getting a number out of it and returning it. I am not modifying any excel sheets or changing the worksheet's environment. Please help!!1
Public Function Operator_Count(Aircraft As String) As Integer
Dim Aircraft_Name As String
Dim Data_Array() As Variant
Dim Row_Count As Integer
Dim Col_Count As Integer
Dim Col_Alph As String
Dim Row_Counter As Integer
Dim Master_Series_Column As Integer
Dim Status_Column As Integer
Dim Operator_Column As Integer
Dim InnerLoop_Counter As Integer
Dim Operator_Array() As Variant
Dim Operator_Array_Transpose() As Variant
Dim Array_Counter As Integer
Aircraft_Name = Aircraft
Operator_Count = 0
'ThisWorkbook.Sheets("Aircraft Data").Activate
Row_Count = ThisWorkbook.Sheets("Aircraft Data").Range("A2", Range("A2").End(xlDown)).Rows.Count
Col_Count = ThisWorkbook.Sheets("Aircraft Data").Cells(1, Columns.Count).End(xlToLeft).Column
Col_Alph = ColumnLetter(Col_Count)
Data_Array = ThisWorkbook.Sheets("Aircraft Data").Range("A1:" & Col_Alph & Row_Count + 1).Value2
For Row_Counter = 1 To Col_Count
If Data_Array(1, Row_Counter) = "Master Series" Then
Master_Series_Column = Row_Counter
End If
Next
For Row_Counter = 1 To Col_Count
If Data_Array(1, Row_Counter) = "Status" Then
Status_Column = Row_Counter
End If
Next
For Row_Counter = 1 To Col_Count
If Data_Array(1, Row_Counter) = "Operator" Then
Operator_Column = Row_Counter
End If
Next
'Resizing the data array
ReDim Operator_Array(0, 0)
'Adding column to the data array
InnerLoop_Counter = 0
For Row_Counter = 1 To UBound(Data_Array)
If Data_Array(Row_Counter, Master_Series_Column) = Aircraft_Name And (Data_Array(Row_Counter, Status_Column) = "In Service" Or Data_Array(Row_Counter, Status_Column) = "On order") Then
Flag = 0
For Array_Counter = 0 To UBound(Operator_Array, 2)
If Operator_Array(0, Array_Counter) = Data_Array(Row_Counter, Operator_Column) Then
Flag = 1
Array_Counter = UBound(Operator_Array, 2)
End If
Next
If Flag <> 1 Then
ReDim Preserve Operator_Array(0, InnerLoop_Counter)
Operator_Array(0, InnerLoop_Counter) = Data_Array(Row_Counter, Operator_Column)
InnerLoop_Counter = InnerLoop_Counter + 1
End If
End If
Next
Operator_Count = UBound(Operator_Array, 2)
End Function
Function ColumnLetter(ColumnNumber As Integer) As String
Dim n As Integer
Dim c As Byte
Dim s As String
n = ColumnNumber
Do
c = ((n - 1) Mod 26)
s = Chr(c + 65) & s
n = (n - c) \ 26
Loop While n > 0
ColumnLetter = s
End Function

Resources