doesnt run for loop - excel

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

Related

xlsm file error upon sending through email

I am a newbie vba coder here.
I have created an .xlsm with userform. Everything works fine in my computer, but when I send the file over via email, the recipient will encounter the following issues when opening the file:
I added an event handler on Workbook_Open to automatically open the userform. When the recipient open the file, it will receive this error and Debug button returns to this line:
When Submit button of the Userform is clicked, the data is supposed to be transferred to 'ThisWorkbook' but instead it creates a new file (i guess the previous version) and paste the data there.
Can anyone help me to figure out what went wrong with my file? Thank you.
Below is my code:
Inside Workbook Event Handler:
Sub Workbook_Open()
RunForm
End Sub
Module1:
Option Explicit
Option Base 1
Sub PopulateComboBox()
Dim PaymentTerms() As String, PaymentFreq() As String, PaymentTermsAlt() As String
Dim i As Integer, j As Integer, m As Integer, n As Integer, o As Integer
j = WorksheetFunction.CountA(Sheets("Populate").Columns("A:A"))
n = WorksheetFunction.CountA(Sheets("Populate").Columns("B:B"))
ReDim PaymentTerms(j - 1) As String
ReDim PaymentFreq(n - 1) As String
ReDim PaymentTermsAlt(j - 1) As String
For i = 1 To j - 1
PaymentTerms(i) = ThisWorkbook.Sheets("Populate").Range("A2:A" & (j - 1)).Cells(i, 1)
UserForm1.ComboTerms.AddItem PaymentTerms(i)
Next i
For m = 1 To n - 1
PaymentFreq(m) = ThisWorkbook.Sheets("Populate").Range("B2:B" & (n - 1)).Cells(m, 1)
UserForm1.ComboFreq.AddItem PaymentFreq(m)
Next m
For o = 1 To j - 1
PaymentTermsAlt(o) = ThisWorkbook.Sheets("Populate").Range("A2:A" & (j - 1)).Cells(o, 1)
UserForm1.ComboTermsAlt.AddItem PaymentTermsAlt(o)
Next o
UserForm1.ComboTerms.Text = PaymentTerms(1)
UserForm1.ComboFreq.Text = PaymentFreq(1)
UserForm1.ComboTermsAlt.Text = PaymentTermsAlt(1)
End Sub
Sub RunForm()
ThisWorkbook.Sheets("Printout").Activate
UserForm1.Show
End Sub
Inside Userform:
Option Explicit
Sub CommandButton1_Click()
Application.ScreenUpdating = False
If Not IsNumeric(BasePay) Or Not IsNumeric(Interest) Then
MsgBox ("Please Enter Numeric Value for Base Pay or Interest Rate")
Exit Sub
End If
If BasePay < 0 Or Interest < 0 Then
MsgBox ("Base Pay or Interest cannot be negative value")
Exit Sub
End If
ThisWorkbook.Sheets("Printout").Range("A1") = "Prepared For " & ClientName
ThisWorkbook.Sheets("Printout").Range("O1").Value = BasePay.Text
ThisWorkbook.Sheets("Printout").Range("S2").Value = Interest.Text / 100
ThisWorkbook.Sheets("Printout").Range("L3").Value = ComboTerms.Text
ThisWorkbook.Sheets("Printout").Range("O3").Value = ComboFreq.Text
ThisWorkbook.Sheets("Printout").Range("Q2").Value = ComboTermsAlt.Text
If NewCar Then
ThisWorkbook.Sheets("Printout").Range("U2").Value = "New"
Else
ThisWorkbook.Sheets("Printout").Range("U2").Value = "Used"
End If
'----- Transfer Add-On Items to Printout Sheet ---------
Dim i As Integer
Dim j As Integer
Dim k As Integer
k = 6
For i = 1 To 9
ThisWorkbook.Sheets("Printout").Cells(k, 1).MergeArea.ClearContents
k = k + 2
Next
k = 6
For i = 10 To 18
ThisWorkbook.Sheets("Printout").Cells(k, 5).MergeArea.ClearContents
k = k + 2
Next
k = 6
For i = 19 To 27
ThisWorkbook.Sheets("Printout").Cells(k, 9).MergeArea.ClearContents
k = k + 2
Next
k = 6
For i = 28 To 36
ThisWorkbook.Sheets("Printout").Cells(k, 13).MergeArea.ClearContents
k = k + 2
Next
'---- Category 1 ------
i = 6
For j = 1 To 9
If UserForm1.Controls("Checkbox" & j).Value = True Then
ThisWorkbook.Sheets("Printout").Range("A" & i).Value = Me.Controls("Checkbox" & j).Caption
i = i + 2
Else
ThisWorkbook.Sheets("Printout").Range("A" & i).Value = ""
End If
Next j
'---- Category 2 ------
i = 6
For j = 10 To 18
If UserForm1.Controls("Checkbox" & j).Value = True Then
ThisWorkbook.Sheets("Printout").Range("E" & i).Value = Me.Controls("Checkbox" & j).Caption
i = i + 2
Else
ThisWorkbook.Sheets("Printout").Range("E" & i).Value = ""
End If
Next j
'---- Category 3 ------
i = 6
For j = 19 To 27
If UserForm1.Controls("Checkbox" & j).Value = True Then
ThisWorkbook.Sheets("Printout").Range("I" & i).Value = Me.Controls("Checkbox" & j).Caption
i = i + 2
Else
ThisWorkbook.Sheets("Printout").Range("I" & i).Value = ""
End If
Next j
'---- Category 4 ------
i = 6
For j = 28 To 36
If UserForm1.Controls("Checkbox" & j).Value = True Then
ThisWorkbook.Sheets("Printout").Range("M" & i).Value = Me.Controls("Checkbox" & j).Caption
i = i + 2
Else
ThisWorkbook.Sheets("Printout").Range("M" & i).Value = ""
End If
Next j
UserForm1.Hide
End Sub
Sub CommandButton2_Click()
Unload UserForm1
UserForm1.Show
End Sub
Sub CommandButton3_Click()
Unload UserForm1
End Sub
Sub NewCar_Click()
Dim LastRow As Integer
Dim i As Integer
Dim j As Integer
LastRow = WorksheetFunction.CountA(Sheets("Populate").Columns("D:D"))
'---- Count No of Checkbox
Dim Ctrl As MSForms.Control
Dim n As Integer
Dim cbcount As Long
For n = 0 To Me.Controls.Count - 1
If Left(UserForm1.Controls(n).Name, 8) = "CheckBox" Then
cbcount = cbcount + 1
End If
Next n
i = 2 '--- Preset counter i
For j = 1 To cbcount
UserForm1.Controls("Checkbox" & j).Caption = ThisWorkbook.Sheets("Populate").Cells(i, 4).Value
i = i + 1
If i > LastRow And i < (cbcount / 4) Then
UserForm1.Controls("Checkbox" & j).Caption = ""
End If
If i > LastRow And i > (cbcount / 4 + 1) Then
i = 2
End If
Next j
End Sub
Sub UsedCar_Click()
Dim LastRow As Integer
Dim i As Integer
Dim j As Integer
LastRow = WorksheetFunction.CountA(Sheets("Populate").Columns("D:D"))
'---- Count No of Checkbox
Dim Ctrl As MSForms.Control
Dim n As Integer
Dim cbcount As Long
For n = 0 To Me.Controls.Count - 1
If Left(Me.Controls(n).Name, 8) = "CheckBox" Then
cbcount = cbcount + 1
End If
Next n
i = 2 '--- Preset counter i
For j = 1 To cbcount
UserForm1.Controls("Checkbox" & j).Caption = ThisWorkbook.Sheets("Populate").Cells(i, 8).Value
i = i + 1
If i > LastRow And i < (cbcount / 4) Then
UserForm1.Controls("Checkbox" & j).Caption = ""
End If
If i > LastRow And i > (cbcount / 4 + 1) Then
i = 2
End If
Next j
End Sub
Sub UserForm_Initialize()
Call PopulateComboBox
'----- Rename Frame Boxes Caption
Dim k As Integer, nc As Integer
nc = 1
For k = 2 To 5
Me.Controls("Frame" & k).Caption = ThisWorkbook.Sheets("Printout").Cells(5, nc)
nc = nc + 4
Next k
'--------------------------------------------------
Dim LastRow As Integer
Dim i As Integer
Dim j As Integer
LastRow = WorksheetFunction.CountA(ThisWorkbook.Sheets("Populate").Columns("D:D"))
'---- Count No of Checkbox
Dim Ctrl As MSForms.Control
Dim n As Integer
Dim cbcount As Long
For n = 0 To Me.Controls.Count - 1
If Left(Me.Controls(n).Name, 8) = "CheckBox" Then
cbcount = cbcount + 1
End If
Next n
i = 2 '--- Preset counter i
For j = 1 To cbcount
UserForm1.Controls("Checkbox" & j).Caption = ThisWorkbook.Sheets("Populate").Cells(i, 4).Value
i = i + 1
If i > LastRow And i < (cbcount / 4) Then
UserForm1.Controls("Checkbox" & j).Caption = ""
End If
If i > LastRow And i > (cbcount / 4 + 1) Then
i = 2
End If
Next j
End Sub

Excel matching with VBA

I am trying to work out the looping on my script but have found it difficult to figure out. I am using this script to find matching data from different sources and reference them together. I would use the built-in functions in excel but it doesn't care about finding the same data more than once.
Read the titles of all the spreadsheets in the book. #Works
Make an array with those titles #Works
Filter out the "current" sheet #Works
Reference each cell in column A on "current" sheet against all the cells on all the pages in column H #Works
If it matches one, take the data from the page it was found on and the data in column G then set that as the value on "current" page in column E #Works
Make the next page in the main sheet array the "current" page and do it all over again #Doesn't Work
I didn't think this would be as complicated as it is, and maybe I'm not helping by not using functions. Got any idea on how to advance inspectSheet correctly?
Sub listsheets()
Dim ws As Worksheet
Dim i As Integer
Dim x As Integer
Dim y As Integer
Dim sheetArray() As Variant
x = 0
y = 0
i = 0
For Each ws In Worksheets
ReDim Preserve sheetArray(i)
sheetArray(i) = ws.Name
i = i + 1
Next ws
Do Until i = 1
i = i - 1
inspectSheet = sheetArray(x)
column = Sheets(inspectSheet).Cells(Rows.Count, "A").End(xlUp).Row
matchArray = Filter(sheetArray, inspectSheet, False, vbTextCompare)
HOLDER = Join(matchArray)
matchSheet = matchArray(y)
Do Until column = 1
currentCell = Sheets(inspectSheet).Cells(column, 1).Value
checkListLength = Sheets(matchSheet).Cells(Rows.Count, "H").End(xlUp).Row
Do Until checkListLength = 1
matchCell = Sheets(matchSheet).Cells(checkListLength, 8).Value
Debug.Print "Checking: " + currentCell + " on " + inspectSheet + " against " + matchCell + " from page " + matchSheet
If currentCell = matchCell Then
Sheets(inspectSheet).Cells(column, 5).Value = matchSheet + " on " + Sheets(matchSheet).Cells(checkListLength, 7).Value
End If
checkListLength = checkListLength - 1
Loop
column = column - 1
Loop
y = y + 1
Loop
x = x + 1
End Sub
I see you already answered your own question, but here's a slightly different approach with fewer counters to track:
Sub listsheets()
Dim wsMatch As Worksheet, wsInspect As Worksheet
Dim currVal
Dim cInspect As Range, cMatch As Range, rngMatch As Range, rngInspect As Range
For Each wsInspect In ThisWorkbook.Worksheets
Set rngInspect = wsInspect.Range("A1:A" & wsInspect.Cells(Rows.Count, "A").End(xlUp).Row)
For Each wsMatch In ThisWorkbook.Worksheets
If wsMatch.Name <> wsInspect.Name Then 'filter out same-name pairs...
Set rngMatch = wsMatch.Range("H1:H" & wsMatch.Cells(Rows.Count, "H").End(xlUp).Row)
For Each cInspect In rngInspect.Cells
currVal = cInspect.Value
For Each cMatch In rngMatch.Cells
If cMatch.Value = currVal Then
cInspect.EntireRow.Columns("E").Value = _
wsMatch.Name & " on " & cMatch.Offset(0, -1).Value
End If
Next cMatch
Next cInspect
End If 'checking these sheets
Next wsMatch
Next wsInspect
End Sub
I got it, I was not resetting my counter variables and needed one more external loop to advance. The finished code is:
Sub listsheets()
Dim ws As Worksheet
Dim i As Integer
Dim x As Integer
Dim y As Integer
Dim limit As Integer
Dim sheetArray() As Variant
x = 0
y = 0
i = 0
For Each ws In Worksheets
ReDim Preserve sheetArray(i)
sheetArray(i) = ws.Name
i = i + 1
Next ws
limit = UBound(sheetArray)
Do Until x = limit
Do Until i = 1
i = i - 1
inspectSheet = sheetArray(x)
Column = Sheets(inspectSheet).Cells(Rows.Count, "A").End(xlUp).Row
matchArray = Filter(sheetArray, inspectSheet, False, vbTextCompare)
HOLDER = Join(matchArray)
matchSheet = matchArray(y)
Do Until Column = 1
currentCell = Sheets(inspectSheet).Cells(Column, 1).Value
checkListLength = Sheets(matchSheet).Cells(Rows.Count, "H").End(xlUp).Row
Do Until checkListLength = 1
matchCell = Sheets(matchSheet).Cells(checkListLength, 8).Value
Debug.Print "Checking: " + currentCell + " on " + inspectSheet + " against " + matchCell + " from page " + matchSheet
If currentCell = matchCell Then
Sheets(inspectSheet).Cells(Column, 5).Value = matchSheet + " on " + Sheets(matchSheet).Cells(checkListLength, 7).Value
End If
checkListLength = checkListLength - 1
Loop
Column = Column - 1
Loop
y = y + 1
Loop
i = UBound(sheetArray)
y = 0
x = x + 1
Loop
End Sub

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

printing gridlines in excel through interop

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

How do I use excel to create random names with values between a certain amount?

I have 100 names in one column. And next to each name in the next cell is a numerical value that the name is worth.There are 6 positions in a company that each name could potentially hold. And that is also in a cell next to each name.
So the spreadsheet looks something like this.
John Smith Lawyer $445352
Joe Doe Doctor $525222
John Doe Accountant $123192
etc....
I want excel to give me 10 people who make a combined amount between 2 and 3 million dollars. But I require that 2 of the people be doctors 2 be lawyers and 2 be accountants etc. How would I create this?
I set up sheet 1 with the following data:
Goal:
Return 10 people
Salary between 1000000 and 6000000 range
Min 2 each doc, lawyer, accountant
Run this Macro:
Sub macro()
Dim rCell As Range
Dim rRng As Range
Dim rangelist As String
Dim entryCount As Long
Dim totalnum As Long
Set rRng = Sheet1.Range("A1:A12")
Dim OccA As String
Dim OccCntA As Long
Dim OccASalmin As Long
Dim OccASalmax As Long
Dim OccB As String
Dim OccCntB As Long
Dim OccBSalmin As Long
Dim OccBSalmax As Long
Dim OccC As String
Dim OccCntC As Long
Dim OccCSalmin As Long
Dim OccCSalmax As Long
'Set total number of results to return
totalnum = 10
'Set which occupations that must be included in results
OccA = "Accountant"
OccB = "Doctor"
OccC = "Lawyer"
'Set minimum quantity of each occupation to me returned in results
OccCntA = 2
OccCntB = 2
OccCntC = 2
'Set min and max salary ranges to return for each occupation
OccASalmin = 1000000
OccASalmax = 6000000
OccBSalmin = 1000000
OccBSalmax = 6000000
OccCSalmin = 1000000
OccCSalmax = 6000000
'Get total number of entries
entryCount = rRng.Count
'Randomly get first required occupation entries
'Return list of rows for each Occupation
OccAList = PickRandomItemsFromList(OccCntA, entryCount, OccA, OccASalmin, OccASalmax)
OccBList = PickRandomItemsFromList(OccCntB, entryCount, OccB, OccBSalmin, OccBSalmax)
OccCList = PickRandomItemsFromList(OccCntC, entryCount, OccC, OccCSalmin, OccCSalmax)
For Each i In OccAList
If rangelist = "" Then
rangelist = "A" & i
Else
rangelist = rangelist & "," & "A" & i
End If
Next i
For Each i In OccBList
If rangelist = "" Then
rangelist = "A" & i
Else
rangelist = rangelist & "," & "A" & i
End If
Next i
For Each i In OccCList
If rangelist = "" Then
rangelist = "A" & i
Else
rangelist = rangelist & "," & "A" & i
End If
Next i
'Print the rows that match criteria
Dim rCntr As Long
rCntr = 1
Dim nRng As Range
Set nRng = Range(rangelist)
For Each j In nRng
Range(j, j.Offset(0, 2)).Select
Selection.Copy
Range("E" & rCntr).Select
ActiveSheet.Paste
rCntr = rCntr + 1
Next j
'Get rest of rows randomly and print
OccList = PickRandomItemsFromListB(totalnum - rCntr + 1, entryCount, rangelist)
For Each k In OccList
Set Rng = Range("A" & k)
Range(Rng, Rng.Offset(0, 2)).Select
Selection.Copy
Range("E" & rCntr).Select
ActiveSheet.Paste
rCntr = rCntr + 1
Next k
End Sub
Function PickRandomItemsFromListB(nItemsToPick As Long, nItemsTotal As Long, avoidRng As String)
Dim rngList As Range
Dim idx() As Long
Dim varRandomItems() As Variant
Dim i As Long
Dim j As Long
Dim booIndexIsUnique As Boolean
Set rngList = Range("B1").Resize(nItemsTotal, 1)
ReDim idx(1 To nItemsToPick)
ReDim varRandomItems(1 To nItemsToPick)
For i = 1 To nItemsToPick
Do
booIndexIsUnique = True ' Innoncent until proven guilty
idx(i) = Int(nItemsTotal * Rnd + 1)
For j = 1 To i - 1
If idx(i) = idx(j) Then
' It's already there.
booIndexIsUnique = False
Exit For
End If
Next j
Set isect = Application.Intersect(Range("A" & idx(i)), Range(avoidRng))
If booIndexIsUnique = True And isect Is Nothing Then
Exit Do
End If
Loop
varRandomItems(i) = idx(i)
Next i
PickRandomItemsFromListB = varRandomItems
' varRandomItems now contains nItemsToPick unique random
' items from range rngList.
End Function
Function PickRandomItemsFromList(nItemsToPick As Long, nItemsTotal As Long, Occ As String, Salmin As Long, Salmax As Long)
Dim rngList As Range
Dim idx() As Long
Dim varRandomItems() As Variant
Dim i As Long
Dim j As Long
Dim booIndexIsUnique As Boolean
Set rngList = Range("B1").Resize(nItemsTotal, 1)
ReDim idx(1 To nItemsToPick)
ReDim varRandomItems(1 To nItemsToPick)
For i = 1 To nItemsToPick
Do
booIndexIsUnique = True ' Innoncent until proven guilty
idx(i) = Int(nItemsTotal * Rnd + 1)
For j = 1 To i - 1
If idx(i) = idx(j) Then
' It's already there.
booIndexIsUnique = False
Exit For
End If
Next j
If booIndexIsUnique = True And Range("B" & idx(i)).Value = Occ And Range("B" & idx(i)).Offset(0, 1).Value >= Salmin And Range("B" & idx(i)).Offset(0, 1).Value <= Salmax Then
Exit Do
End If
Loop
varRandomItems(i) = idx(i)
Next i
PickRandomItemsFromList = varRandomItems
End Function
Results are printed in column E with the first results meeting the criteria. After those, the rest are random but don't repeat the previous ones:
I'm not doing very much error checking such as what happens if there are not 2 doctors or not enough entries left to meet the required number of results. You'll have to fine tune it for your purposes. You'll probably also want to set up the inputs as a form so you don't have to mess with code every time you change your criteria.

Resources