البحث في الموقع
Showing results for tags 'ابو جوى'.
تم العثور علي 6 نتائج
-
السلام عليكم ورحمة الله تعالى وبركاته هدية اليوم هى عبارة عن مكتبة برمجية متكاملة تم كتابتها وتطويرها لتوفير حلول مرنة وقوية لضغط الملفات والمجلدات وفك ضغطها باستخدام أدوات شائعة مثل WinRAR و7-Zip لأتمتة عمليات الضغط وفك الضغط للملفات و المجلدات بإحترافيه ومرونه وتحكم شامل فيما يلي نبذة عن الخصائص والمميزات والإمكانيات العامة للكود : يدعم ضغط الملفات وفك ضغطها باستخدام كل من WinRAR و7-Zip مما يتيح للمستخدم اختيار الأداة المناسبة بناء على احتياجاته يقبل المدخلات على شكل سلسلة نصية واحدة أو مصفوفة تحتوي على عدة ملفات أو مجلدات يحدد تلقائيا مسارات البرامج من سجل النظام أو المسارات الافتراضية مع خيار يدوي كبديل يستخدم ترميز Unicode في ملفات التعليق لدعم النصوص العربية وغيرها من اللغات يوفر 6 مستويات (من بدون ضغط إلى أقصى ضغط ) للتحكم في التوازن بين السرعة وحجم الملف يدعم تقسيم الأرشيف إلى أجزاء بأحجام مختلفة (50 ميجابايت إلى 2 جيجابايت) يتيح إضافة كلمة مرور للأرشيفات مع تشفير أسماء الملفات أرشيفات ذاتية الاستخراج (SFX): يمكن إنشاء ملفات تنفيذية (exe) لا تحتاج إلى برنامج لفك الضغط التعليقات: يدعم إضافة تعليقات نصية للأرشيفات في WinRAR إدارة عمليات متعددة: ضغط وفك ضغط عدة ملفات في استدعاء واحد أو عبر حلقات ( مصفوفات ) يحتوي على معالجة أخطاء شاملة مع رسائل توضيحية (مثل أخطاء المعاملات أو الملفات غير الموجودة) التخصيص:يسمح بتحديد اسم الأرشيف - المسار الهدف - ونوع الأرشيف (RAR/ZIP/7z) حسب رغبة المستخدم سيناريوهات الاستخدام ضغط التقارير أو المستندات الكبيرة وتوزيعها بسهولة إنشاء أرشيفات محمية بكلمة مرور أو ذاتية الاستخراج لمشاركة الملفات دمج الكود في تطبيقات إدارية لتبسيط عمليات النسخ الاحتياطي أو الأرشفة نقاط القوة سهولة الاستخدام: يمكن تصميم واجهة بسيطة مع معاملات اختيارية ذات قيم افتراضية منطقية الأداء: يعتمد على أدوات مثبتة مثل WinRAR و7-Zip لضمان السرعة والكفاءة التوثيق: الاهتمام بالتعليقات الشاملة داخل الكود لتسهيل فهم الكود وصيانته القيود النظرية يتطلب تثبيت WinRAR أو 7-Zip مسبقا بعض الميزات (مثل التعليقات) مدعومة فقط في WinRAR مبدئيا الأفكار والأكواد حتى الآن قيد التجربــــــه من أجل ذلك : فى حال وقوع اى مشاكل عند التجارب برجاء إخبارى فورا .. ولكم جزيل الشكر وأخيـــــــــرا الكــــــــــــــود الكود داخل وحده نمطية عامة باسم : basArchiveUtility ' يضمن مقارنة النصوص بناءً على إعدادات قاعدة البيانات (مثل ترتيب الحروف واللغة) Option Compare Database ' يجبر على تعريف المتغيرات صراحة قبل استخدامها، مما يمنع الأخطاء الناتجة عن الأسماء الخاطئة Option Explicit ' تعريف تعداد لمستويات الضغط المدعومة Enum EnumCompressionLevel CompressionNone = 0 ' بدون ضغط (تخزين فقط) CompressionFastest = 1 ' أسرع ضغط (حجم أكبر، سرعة عالية) CompressionFast = 3 ' ضغط سريع (توازن بين السرعة والحجم) CompressionNormal = 5 ' ضغط عادي (الافتراضي في معظم الأدوات) CompressionMaximum = 7 ' ضغط أقصى (حجم أصغر، أبطأ) CompressionUltra = 9 ' ضغط فائق (أقصى تقليص للحجم، أبطأ جدًا) End Enum ' تعريف تعداد لخيارات تقسيم حجم الأرشيف لدعم تقسيم الملفات الكبيرة Enum EnumSplitSizeOption ' بدون تقسيم (أرشيف واحد) SplitNone = 0 ' تقسيم إلى أجزاء بحجم 50 ميجابايت Split50MB = 50 ' تقسيم إلى أجزاء بحجم 100 ميجابايت Split100MB = 100 ' تقسيم إلى أجزاء بحجم 200 ميجابايت Split200MB = 200 ' تقسيم إلى أجزاء بحجم 500 ميجابايت Split500MB = 500 ' تقسيم إلى أجزاء بحجم 1 جيجابايت Split1GB = 1000 ' تقسيم إلى أجزاء بحجم 2 جيجابايت Split2GB = 2000 End Enum ' تعريف تعداد لأوضاع الكتابة فوق الملفات الموجودة مسبقًا Enum EnumOverwriteMode ' عدم الكتابة فوق الملفات (تجاهل العملية إذا وجد الملف) OverwriteNone = 0 ' طلب تأكيد من المستخدم عند وجود ملف OverwritePrompt = 1 ' الكتابة فوق جميع الملفات الموجودة تلقائيًا OverwriteAll = 2 End Enum ' تعريف تعداد لتحديد أداة الأرشفة المستخدمة Enum EnumArchiveMethod ' استخدام WinRAR كأداة ضغط WinRAR = 0 ' استخدام 7-Zip كأداة ضغط SevenZip = 1 End Enum ' تعريف تعداد لأنواع الأرشيف المدعومة Enum EnumArchiveType ' أرشيف بصيغة RAR (شائعة الاستخدام مع WinRAR) ArchiveRAR = 0 ' أرشيف بصيغة ZIP (صيغة قياسية مدعومة على نطاق واسع) ArchiveZIP = 1 ' أرشيف بصيغة 7z (صيغة مفتوحة المصدر توفر ضغطًا عاليًا مع 7-Zip) Archive7z = 2 ' أرشيف بصيغة TAR (يستخدم عادة في أنظمة Unix/Linux لتجميع الملفات بدون ضغط) ArchiveTAR = 3 ' أرشيف بصيغة GZ (Gzip، ضغط فعال لملف واحد) ArchiveGZ = 4 ' أرشيف بصيغة BZIP2 (ضغط قوي مشابه لـ GZ ولكن بكفاءة أعلى في بعض الحالات) ArchiveBZ2 = 5 ' أرشيف بصيغة XZ (صيغة حديثة توفر ضغطًا عاليًا، مدعومة بواسطة 7-Zip وأدوات أخرى) ArchiveXZ = 6 ' أرشيف بصيغة ISO (صورة قرص مضغوطة، يمكن التعامل معها بواسطة أدوات مثل 7-Zip أو WinRAR) ArchiveISO = 7 ' أرشيف بصيغة CAB (صيغة Microsoft Cabinet، تُستخدم في ملفات التثبيت) ArchiveCAB = 8 ' أرشيف بصيغة Z (صيغة ضغط قديمة، لا تزال مدعومة في بعض الأدوات) ArchiveZ = 9 ' أرشيف بصيغة LZH (صيغة ضغط يابانية قديمة، مدعومة بواسطة WinRAR وغيرها) ArchiveLZH = 10 ' أرشيف بصيغة ARJ (صيغة ضغط قديمة، لا تزال مدعومة بواسطة بعض الأدوات مثل WinRAR) ArchiveARJ = 11 End Enum ' متغير عام للتحكم في حالة الحلقات (مثل السماح بإيقاف عملية متكررة) Public IsInLoop As Boolean ' متغير عام لتخزين قائمة بالأرشيفات الناتجة (مثل مسارات الملفات المضغوطة) Public ArchivesList As String ' تعريف متغيرات عامة ثابتة لتخزين مسارات الأدوات المختارة يدويًا ' تحافظ على القيمة طوال جلسة تشغيل قاعدة البيانات Private m_WinRARPath As String ' مسار WinRAR المختار يدويًا Private m_SevenZipPath As String ' مسار 7-Zip المختار يدويًا ' دالة مساعدة لتحويل مستوى الضغط إلى تنسيق WinRAR (مثل -m0 إلى -m5) Function GetWinRARCompressionLevel(compressionLevel As EnumCompressionLevel) As String Select Case compressionLevel Case CompressionNone: GetWinRARCompressionLevel = "-m0" ' بدون ضغط Case CompressionFastest: GetWinRARCompressionLevel = "-m1" ' أسرع ضغط Case CompressionFast: GetWinRARCompressionLevel = "-m2" ' ضغط سريع Case CompressionNormal: GetWinRARCompressionLevel = "-m3" ' ضغط عادي Case CompressionMaximum: GetWinRARCompressionLevel = "-m5" ' ضغط أقصى Case CompressionUltra: GetWinRARCompressionLevel = "-m5" ' ضغط فائق (WinRAR لا يدعم 9) End Select End Function ' دالة مساعدة لتحويل مستوى الضغط إلى تنسيق 7-Zip (مثل mx0 إلى mx9) Function Get7ZipCompressionLevel(compressionLevel As EnumCompressionLevel) As String Select Case compressionLevel Case CompressionNone: Get7ZipCompressionLevel = "-mx0" ' بدون ضغط Case CompressionFastest: Get7ZipCompressionLevel = "-mx1" ' أسرع ضغط Case CompressionFast: Get7ZipCompressionLevel = "-mx3" ' ضغط سريع Case CompressionNormal: Get7ZipCompressionLevel = "-mx5" ' ضغط عادي Case CompressionMaximum: Get7ZipCompressionLevel = "-mx7" ' ضغط أقصى Case CompressionUltra: Get7ZipCompressionLevel = "-mx9" ' ضغط فائق End Select End Function ' دالة مساعدة لتحديد نوع الأرشيف لـ 7-Zip (مثل "zip"، "7z"، إلخ) Function Get7ZipArchiveType(ArchiveType As EnumArchiveType) As String Select Case ArchiveType Case ArchiveRAR: Get7ZipArchiveType = "rar" ' نوع RAR Case ArchiveZIP: Get7ZipArchiveType = "zip" ' نوع ZIP Case Archive7z: Get7ZipArchiveType = "7z" ' نوع 7z Case ArchiveTAR: Get7ZipArchiveType = "tar" ' نوع TAR Case ArchiveGZ: Get7ZipArchiveType = "gzip" ' نوع GZ Case ArchiveBZ2: Get7ZipArchiveType = "bzip2" ' نوع BZIP2 Case ArchiveXZ: Get7ZipArchiveType = "xz" ' نوع XZ Case ArchiveISO: Get7ZipArchiveType = "iso" ' نوع ISO Case ArchiveCAB: Get7ZipArchiveType = "cab" ' نوع CAB Case ArchiveZ: Get7ZipArchiveType = "z" ' نوع Z Case ArchiveLZH: Get7ZipArchiveType = "lzh" ' نوع LZH Case ArchiveARJ: Get7ZipArchiveType = "arj" ' نوع ARJ End Select End Function ' دالة لإرجاع امتداد الملف بناءً على نوع الأرشيف المحدد في EnumArchiveType Function GetArchiveExtension(ArchiveType As EnumArchiveType) As String Select Case ArchiveType Case ArchiveRAR: GetArchiveExtension = ".rar" ' امتداد لأرشيف RAR Case ArchiveZIP: GetArchiveExtension = ".zip" ' امتداد لأرشيف ZIP Case Archive7z: GetArchiveExtension = ".7z" ' امتداد لأرشيف 7z Case ArchiveTAR: GetArchiveExtension = ".tar" ' امتداد لأرشيف TAR Case ArchiveGZ: GetArchiveExtension = ".gz" ' امتداد لأرشيف GZ (Gzip) Case ArchiveBZ2: GetArchiveExtension = ".bz2" ' امتداد لأرشيف BZIP2 Case ArchiveXZ: GetArchiveExtension = ".xz" ' امتداد لأرشيف XZ Case ArchiveISO: GetArchiveExtension = ".iso" ' امتداد لأرشيف ISO Case ArchiveCAB: GetArchiveExtension = ".cab" ' امتداد لأرشيف CAB Case ArchiveZ: GetArchiveExtension = ".z" ' امتداد لأرشيف Z Case ArchiveLZH: GetArchiveExtension = ".lzh" ' امتداد لأرشيف LZH Case ArchiveARJ: GetArchiveExtension = ".arj" ' امتداد لأرشيف ARJ End Select End Function ' دالة لتحويل خيار تقسيم الحجم من تعداد EnumSplitSizeOption إلى سلسلة متوافقة مع أوامر 7-Zip أو WinRAR ' المدخل: خيار التقسيم من نوع EnumSplitSizeOption ' المخرج: سلسلة نصية تمثل حجم التقسيم (مثل "1g" أو "500m") أو سلسلة فارغة إذا لم يكن هناك تقسيم Function GetSplitSizeString(sizeOption As EnumSplitSizeOption) As String Select Case sizeOption Case SplitNone: GetSplitSizeString = "" ' بدون تقسيم Case Split50MB: GetSplitSizeString = "50m" ' 50 ميجابايت Case Split100MB: GetSplitSizeString = "100m" ' 100 ميجابايت Case Split200MB: GetSplitSizeString = "200m" ' 200 ميجابايت Case Split500MB: GetSplitSizeString = "500m" ' 500 ميجابايت Case Split1GB: GetSplitSizeString = "1g" ' 1 جيجابايت Case Split2GB: GetSplitSizeString = "2g" ' 2 جيجابايت End Select End Function ' دالة للتحقق من صحة المسار (عدم وجود أحرف غير قانونية أو تعقيدات غير مرغوبة) ' المدخل: سلسلة تمثل المسار المراد التحقق منه ' المخرج: قيمة منطقية (True إذا كان المسار صالحًا، False إذا كان غير صالح) Function IsValidPath(filePath As String) As Boolean On Error GoTo ErrorHandler ' تعريف الأحرف غير القانونية في مسارات Windows Dim invalidChars As String invalidChars = "\/:*?""<>|" ' متغير للتنقل عبر الأحرف غير القانونية Dim i As Integer ' فحص كل حرف غير قانوني في المسار For i = 1 To Len(invalidChars) ' إذا وُجد حرف غير قانوني، أنهِ الدالة وأرجع False If InStr(filePath, Mid(invalidChars, i, 1)) > 0 Then Exit Function Next i ' التحقق من أن المسار لا يحتوي على ".." (لمنع التنقل غير المرغوب) وأنه غير فارغ IsValidPath = (InStr(filePath, "..\") = 0) And (Len(filePath) > 0) Exit Function ErrorHandler: ' في حالة حدوث خطأ (مثل قيمة غير صالحة لـ filePath)، أرجع False IsValidPath = False End Function ' دالة لتنظيف المدخلات من الأحرف غير المرغوبة التي قد تسبب مشاكل في تنفيذ الأوامر ' المدخل: سلسلة نصية تحتاج إلى تنظيف ' المخرج: سلسلة نصية منقاة من الأحرف المحددة Function SanitizeInput(inputString As String) As String ' إزالة علامات الاقتباس المزدوجة لمنع مشاكل في بناء الأوامر SanitizeInput = Replace(inputString, """", "") ' إزالة رمز "&" لمنع تنفيذ أوامر متتالية غير مقصودة SanitizeInput = Replace(SanitizeInput, "&", "") ' إزالة رمز "|" لمنع توجيه الأوامر بشكل غير متوقع SanitizeInput = Replace(SanitizeInput, "|", "") End Function ' دالة للسماح للمستخدم باختيار مسار أداة الأرشفة يدويًا باستخدام نافذة حوار الملفات ' المدخل: اسم الأداة ("WinRAR" أو "SevenZip") ' المخرج: مسار الملف التنفيذي المختار (مثل "WinRAR.exe" أو "7z.exe")، أو سلسلة فارغة إذا فشل الاختيار Function SelectArchivePathManually(Method As String) As String On Error GoTo ErrorHandler ' التحقق من صحة المدخل للتأكد من أنه إما "WinRAR" أو "SevenZip" If Method <> "WinRAR" And Method <> "SevenZip" Then MsgBox "قيمة غير صالحة: " & Method, vbCritical ' عرض رسالة خطأ إذا كان المدخل غير صالح Exit Function ' الخروج من الدالة إذا لم يكن المدخل صحيحًا End If ' إنشاء كائن نافذة حوار الملفات للسماح للمستخدم باختيار ملف تنفيذي Dim fileDialog As Object Set fileDialog = Application.fileDialog(3) ' نوع 3 يمثل نافذة اختيار الملفات With fileDialog ' تعيين عنوان النافذة بناءً على الأداة المطلوبة لتوجيه المستخدم .Title = IIf(Method = "WinRAR", "اختر WinRAR.exe", "اختر 7z.exe") ' مسح أي فلاتر سابقة لضمان عرض الفلتر الجديد فقط .Filters.Clear ' إضافة فلتر لعرض الملفات التنفيذية (*.exe) فقط لتسهيل الاختيار .Filters.Add "Executable", "*.exe" ' منع اختيار أكثر من ملف واحد لضمان اختيار ملف واحد فقط .AllowMultiSelect = False ' عرض نافذة الحوار والتحقق مما إذا ضغط المستخدم على "موافق" (-1) If .Show = -1 Then ' تخزين المسار المختار من العنصر الأول (والوحيد) في قائمة العناصر المختارة Dim selectedPath As String selectedPath = .SelectedItems(1) ' التحقق من أن الملف المختار يتطابق مع الأداة المطلوبة (WinRAR.exe أو 7z.exe) If (Method = "WinRAR" And InStr(LCase(selectedPath), "winrar.exe") = 0) Or _ (Method = "SevenZip" And InStr(LCase(selectedPath), "7z.exe") = 0) Then MsgBox "الملف غير صحيح!", vbExclamation ' عرض تحذير إذا لم يكن الملف المختار صحيحًا Exit Function ' الخروج إذا كان الملف غير مطابق End If ' إرجاع المسار المختار إذا كان صالحًا SelectArchivePathManually = selectedPath End If End With Exit Function ErrorHandler: ' معالجة أي خطأ يحدث أثناء تنفيذ الدالة (مثل فشل إنشاء نافذة الحوار) MsgBox "خطأ في اختيار المسار: " & Err.Description, vbCritical End Function ' دالة اختيارية لإعادة تعيين المسارات المخزنة (يمكن استدعاؤها عند الحاجة) Public Sub ResetArchivePaths() m_WinRARPath = "" ' إعادة تعيين مسار WinRAR المخزن m_SevenZipPath = "" ' إعادة تعيين مسار 7-Zip المخزن End Sub ' دالة لتحديد مسار أداة الأرشفة تلقائيًا من السجل أو المسارات الافتراضية، مع الرجوع إلى الاختيار اليدوي المخزن إذا لزم الأمر ' المدخل: اسم الأداة ("WinRAR" أو "SevenZip") ' المخرج: مسار الملف التنفيذي للأداة (مثل "WinRAR.exe" أو "7z.exe")، أو سلسلة فارغة إذا فشل التحديد Function DetermineArchivePath(Method As String) As String On Error GoTo ErrorHandler ' التحقق من صحة المدخل للتأكد من أنه إما "WinRAR" أو "SevenZip" If Method <> "WinRAR" And Method <> "SevenZip" Then MsgBox "قيمة غير صالحة: " & Method, vbCritical ' عرض رسالة خطأ إذا كان المدخل غير صالح Exit Function ' الخروج إذا كان المدخل غير صالح End If ' التحقق مما إذا كان المسار مخزنًا مسبقًا في المتغير العام المناسب If Method = "WinRAR" And m_WinRARPath <> "" Then DetermineArchivePath = m_WinRARPath ' إرجاع المسار المخزن لـ WinRAR إذا كان موجودًا Exit Function ElseIf Method = "SevenZip" And m_SevenZipPath <> "" Then DetermineArchivePath = m_SevenZipPath ' إرجاع المسار المخزن لـ 7-Zip إذا كان موجودًا Exit Function End If ' إنشاء كائن للوصول إلى السجل (Registry) لاستخراج المسارات المثبتة Dim reg As Object Dim p As Variant ' متغير للتنقل عبر المسارات الافتراضية Set reg = CreateObject("WScript.Shell") Dim pathFromReg As String ' متغير لتخزين المسار المستخرج من السجل If Method = "WinRAR" Then ' محاولة استخراج مسار WinRAR من السجل باستخدام مفاتيح مختلفة On Error Resume Next ' تعطيل معالجة الأخطاء للتعامل مع مفاتيح غير موجودة pathFromReg = reg.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe\") If Err.Number <> 0 Then pathFromReg = reg.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\WinRAR\exe32") If Err.Number <> 0 Then pathFromReg = reg.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\WinRAR\exe32") On Error GoTo 0 ' إعادة تفعيل معالجة الأخطاء ' التحقق مما إذا تم العثور على مسار صالح في السجل وأن الملف موجود If pathFromReg <> "" And Dir(pathFromReg) <> "" Then m_WinRARPath = pathFromReg ' تخزين المسار في المتغير العام لـ WinRAR DetermineArchivePath = pathFromReg ' إرجاع المسار المستخرج Exit Function End If ' فحص المسارات الافتراضية لـ WinRAR إذا لم يتم العثور على المسار في السجل Dim defaultPaths defaultPaths = Array("C:\Program Files\WinRAR\WinRAR.exe", "C:\Program Files (x86)\WinRAR\WinRAR.exe") For Each p In defaultPaths If Dir(p) <> "" Then m_WinRARPath = p ' تخزين المسار في المتغير العام لـ WinRAR DetermineArchivePath = p ' إرجاع المسار الافتراضي الصالح Exit Function End If Next p ElseIf Method = "SevenZip" Then ' محاولة استخراج مسار 7-Zip من السجل باستخدام مفاتيح مختلفة On Error Resume Next ' تعطيل معالجة الأخطاء للتعامل مع مفاتيح غير موجودة pathFromReg = reg.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\7-Zip\Path") If Err.Number <> 0 Then pathFromReg = reg.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\7-Zip\Path") On Error GoTo 0 ' إعادة تفعيل معالجة الأخطاء ' التحقق من المسار وإضافة "7z.exe" إذا كان المسار صالحًا If pathFromReg <> "" Then If Right(pathFromReg, 1) <> "\" Then pathFromReg = pathFromReg & "\" ' التأكد من وجود "\" في نهاية المسار If Dir(pathFromReg & "7z.exe") <> "" Then m_SevenZipPath = pathFromReg & "7z.exe" ' تخزين المسار في المتغير العام لـ 7-Zip DetermineArchivePath = pathFromReg & "7z.exe" ' إرجاع المسار الكامل Exit Function End If End If ' فحص المسارات الافتراضية لـ 7-Zip إذا لم يتم العثور على المسار في السجل defaultPaths = Array("C:\Program Files\7-Zip\7z.exe", CurrentProject.Path & "\7-Zip64\7z.exe", "C:\Program Files (x86)\7-Zip\7z.exe", CurrentProject.Path & "\7-Zip86\7z.exe") For Each p In defaultPaths If Dir(p) <> "" Then m_SevenZipPath = p ' تخزين المسار في المتغير العام لـ 7-Zip DetermineArchivePath = p ' إرجاع المسار الافتراضي الصالح Exit Function End If Next p End If ' إذا فشلت جميع الطرق التلقائية، استدعاء الاختيار اليدوي وتخزين النتيجة Dim manualPath As String manualPath = SelectArchivePathManually(Method) ' استدعاء الدالة للاختيار اليدوي If manualPath <> "" Then If Method = "WinRAR" Then m_WinRARPath = manualPath ' تخزين المسار اليدوي لـ WinRAR في المتغير العام ElseIf Method = "SevenZip" Then m_SevenZipPath = manualPath ' تخزين المسار اليدوي لـ 7-Zip في المتغير العام End If DetermineArchivePath = manualPath ' إرجاع المسار المختار يدويًا End If Exit Function ErrorHandler: ' معالجة أي خطأ يحدث أثناء تنفيذ الدالة (مثل فشل الوصول إلى السجل) MsgBox "خطأ في تحديد المسار: " & Err.Description, vbCritical End Function ' دالة لإنشاء ملف نصي مؤقت يحتوي على تعليقات (سطر واحد أو عدة أسطر) مع خيار الحذف بعد الاستخدام ' المدخل: ' - commentLines: نص أو مصفوفة من النصوص تمثل التعليقات المراد كتابتها في الملف ' - deleteAfterUse: قيمة منطقية اختيارية (True افتراضيًا) لتحديد ما إذا كان سيتم حذف الملف بعد إنشائه ' المخرج: مسار الملف النصي المؤقت الذي تم إنشاؤه ' دالة لإنشاء ملف تعليقات مؤقت وإرجاع مساره Function CreateCommentFile(commentLines As Variant) As String Dim fso As Object Dim tempFile As String Dim file As Object Dim line As Variant Set fso = CreateObject("Scripting.FileSystemObject") tempFile = CurrentProject.Path & "\temp_comment.txt" Set file = fso.CreateTextFile(tempFile, True, True) If IsArray(commentLines) Then For Each line In commentLines file.WriteLine CStr(line) Next line Else file.WriteLine CStr(commentLines) End If file.Close CreateCommentFile = tempFile ' إرجاع المسار بدون حذف Set file = Nothing Set fso = Nothing End Function ' دالة لبناء أمر ضغط الملفات/المجلدات بناءً على الخيارات المحددة باستخدام WinRAR أو 7-Zip ' المدخلات: ' - sourceFile: ملف أو مصفوفة ملفات/مجلدات للضغط (قد تكون مسارات نسبية أو مطلقة) ' - password: كلمة المرور لتشفير الأرشيف (اختياري) ' - Method: أداة الضغط (WinRAR أو SevenZip) من EnumArchiveMethod ' - archiveType: نوع الأرشيف (RAR، ZIP، 7z، إلخ) من EnumArchiveType ' - compressionLevel: مستوى الضغط من EnumCompressionLevel ' - partSize: حجم التقسيم (إن وجد) من EnumSplitSizeOption ' - targetPath: مسار حفظ الأرشيف (اختياري، يُستخدم المشروع الحالي إذا لم يُحدد) ' - archiveName: اسم الأرشيف (اختياري، يُشتق من الملف الأصلي إذا لم يُحدد) ' - isSFX: تحديد ما إذا كان الأرشيف سيكون تنفيذيًا ذاتيًا (Self-Extracting) ' - commentFile: مسار ملف التعليقات (اختياري) ' - deleteOriginals: حذف الملفات الأصلية بعد الضغط ' المخرج: سلسلة نصية تمثل الأمر الكامل للضغط Function BuildCompressCommand( _ sourceFile As Variant, _ password As String, _ Method As EnumArchiveMethod, _ ArchiveType As EnumArchiveType, _ compressionLevel As EnumCompressionLevel, _ partSize As EnumSplitSizeOption, _ targetPath As String, _ archiveName As String, _ isSFX As Boolean, _ commentFile As String, _ Optional ByVal deleteOriginals As Boolean = True) As String ' تعريف المتغيرات اللازمة لبناء الأمر Dim Command As String ' الأمر النهائي الذي سيتم إرجاعه Dim archiveProgramPath As String ' مسار أداة الضغط (WinRAR.exe أو 7z.exe) Dim fileList As String ' قائمة الملفات/المجلدات للضغط Dim targetFile As String ' المسار الكامل للأرشيف الناتج Dim fso As Object ' كائن FileSystemObject للتعامل مع الملفات Dim file As Variant ' متغير للتنقل عبر الملفات في المصفوفة Dim fullFilePath As String ' المسار الكامل لكل ملف/مجلد ' On Error GoTo ErrorHandler ' إنشاء كائن FileSystemObject للتحقق من الملفات والمسارات Set fso = CreateObject("Scripting.FileSystemObject") '--- معالجة المسارات النسبية --- fileList = "" ' تهيئة قائمة الملفات ' تحويل المدخل إلى مصفوفة إذا لم يكن كذلك لتسهيل المعالجة If Not IsArray(sourceFile) Then sourceFile = Array(sourceFile) ' معالجة كل ملف/مجلد في المصفوفة For Each file In sourceFile ' تحديد المسار الكامل بناءً على كونه نسبيًا أو مطلقًا If InStr(file, ":\") = 0 And InStr(file, "\\") = 0 Then ' مسار نسبي (لا يحتوي على محرك أقراص أو مسار شبكة) If Left(file, 1) = "\" Then ' يبدأ بـ "\" (مثل \folder\file.txt)، يُضاف إلى مسار المشروع مباشرة fullFilePath = CurrentProject.Path & file Else ' مسار نسبي عادي (مثل folder\file.txt)، يُضاف مع فاصل "\" fullFilePath = CurrentProject.Path & "\" & file End If Else ' مسار مطلق (مثل C:\...\file.txt)، يُستخدم كما هو fullFilePath = file End If ' التحقق من وجود الملف أو المجلد في المسار المحدد If Not fso.FileExists(fullFilePath) And Not fso.FolderExists(fullFilePath) Then MsgBox "المسار غير موجود: " & fullFilePath, vbCritical Exit Function ' الخروج إذا لم يكن المسار موجودًا End If ' إضافة المسار المنظف إلى قائمة الملفات مع إحاطته بعلامات اقتباس fileList = fileList & " """ & SanitizeInput(fullFilePath) & """" Next file '--- تحديد مسار الأرشيف الناتج --- If targetPath = "" Then ' إذا لم يُحدد مسار الهدف، استخدام مسار المشروع الحالي targetPath = CurrentProject.Path End If '--- بناء اسم الأرشيف --- targetFile = targetPath & "\" & _ IIf(archiveName = "", fso.GetBaseName(sourceFile(LBound(sourceFile))), archiveName) & _ IIf(isSFX, ".exe", _ IIf(ArchiveType = ArchiveRAR, ".rar", _ IIf(ArchiveType = ArchiveZIP, ".zip", ".7z"))) ' الشرح: ' - إذا لم يُحدد اسم الأرشيف، يُشتق من اسم الملف الأول (بدون الامتداد) ' - إذا كان SFX، يُستخدم امتداد ".exe"، وإلا يُحدد الامتداد بناءً على نوع الأرشيف (RAR، ZIP، 7z) '--- التحقق من صحة الأداة --- archiveProgramPath = DetermineArchivePath(IIf(Method = WinRAR, "WinRAR", "SevenZip")) If archiveProgramPath = "" Then Exit Function ' الخروج إذا لم يتم العثور على الأداة '--- بناء الأمر بناءً على الأداة --- If Method = WinRAR Then ' بناء أمر WinRAR Command = """" & archiveProgramPath & """ a -ep1 -m" & compressionLevel ' - "a": إضافة الملفات إلى الأرشيف ' - "-ep1": استبعاد المسار الأساسي من الأسماء داخل الأرشيف ' - "-m": تحديد مستوى الضغط (0-5) Command = Command & IIf(isSFX, " -sfx", "") ' إضافة خيار SFX إذا تم تحديده Command = Command & " """ & targetFile & """" & fileList ' إضافة مسار الأرشيف وقائمة الملفات Command = Command & IIf(password <> "", " -p" & SanitizeInput(password), "") ' إضافة كلمة المرور إذا وُجدت Command = Command & IIf(partSize <> SplitNone, " -v" & GetSplitSizeString(partSize), "") ' إضافة خيار التقسيم إذا تم تحديده Command = Command & IIf(commentFile <> "" And fso.FileExists(commentFile), " -z""" & commentFile & """", "") ' إضافة ملف التعليقات إذا وُجد Command = Command & IIf(deleteOriginals, " -df", "") ' حذف الملفات الأصلية بعد الضغط إذا تم تحديده ElseIf Method = SevenZip Then ' بناء أمر 7-Zip Command = """" & archiveProgramPath & """ a -mx=" & Get7ZipCompressionLevel(compressionLevel) ' - "a": إضافة الملفات إلى الأرشيف ' - "-mx=": تحديد مستوى الضغط (0-9) باستخدام دالة GetSevenZipCompressionLevel Command = Command & IIf(isSFX, " -sfx7z.sfx", "") ' إضافة خيار SFX باستخدام ملف 7z.sfx Command = Command & " """ & targetFile & """" & fileList ' إضافة مسار الأرشيف وقائمة الملفات Command = Command & IIf(password <> "", " -p" & SanitizeInput(password) & " -mhe=on", "") ' إضافة كلمة المرور مع تشفير الأسماء Command = Command & IIf(partSize <> SplitNone, " -v" & GetSplitSizeString(partSize), "") ' إضافة خيار التقسيم إذا تم تحديده Command = Command & IIf(deleteOriginals, " -sdel", "") ' حذف الملفات الأصلية بعد الضغط إذا تم تحديده End If ' إرجاع الأمر النهائي BuildCompressCommand = Command Exit Function ' 'ErrorHandler: ' ' معالجة الأخطاء وعرض رسالة في حالة حدوث مشكلة (مثل مسار غير صالح أو فشل إنشاء الكائن) ' MsgBox "خطأ في بناء الأمر: " & Err.Description, vbCritical End Function ' إجراء لضغط العناصر (ملفات أو مجلدات) باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة ' المدخلات (جميعها اختيارية): ' - itemsArray: ملف أو مصفوفة ملفات/مجلدات للضغط ' - password: كلمة المرور لتشفير الأرشيف (افتراضي: فارغ) ' - Method: أداة الضغط (افتراضي: SevenZip) ' - archiveType: نوع الأرشيف (افتراضي: Archive7z) ' - compressionLevel: مستوى الضغط (افتراضي: CompressionNormal) ' - partSize: حجم التقسيم (افتراضي: SplitNone) ' - targetPath: مسار حفظ الأرشيف (افتراضي: فارغ، يُستخدم المشروع الحالي) ' - archiveName: اسم الأرشيف (افتراضي: فارغ، يُشتق من الملف الأصلي) ' - isSFX: تحديد ما إذا كان الأرشيف تنفيذيًا ذاتيًا (افتراضي: False) ' - commentFile: مسار ملف التعليقات (افتراضي: فارغ) ' - deleteOriginals: حذف الملفات الأصلية بعد الضغط (افتراضي: False) ' إجراء لضغط العناصر باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة ' إجراء لضغط العناصر باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة ' إجراء لضغط العناصر باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة Sub CompressItems( _ Optional ByVal itemsArray As Variant, _ Optional ByVal password As String = "", _ Optional ByVal Method As EnumArchiveMethod = SevenZip, _ Optional ByVal ArchiveType As EnumArchiveType = Archive7z, _ Optional ByVal compressionLevel As EnumCompressionLevel = CompressionNormal, _ Optional ByVal partSize As EnumSplitSizeOption = SplitNone, _ Optional ByVal targetPath As String = "", _ Optional ByVal archiveName As String = "", _ Optional ByVal isSFX As Boolean = False, _ Optional ByVal commentFile As String = "", _ Optional ByVal deleteOriginals As Boolean = False) Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") On Error GoTo ErrorHandler If VarType(itemsArray) = vbEmpty Then MsgBox "لم يتم تحديد عناصر للضغط!", vbExclamation Exit Sub End If ' تحويل itemsArray إلى مصفوفة إذا كان سلسلة نصية واحدة Dim items As Variant If Not IsArray(itemsArray) Then items = Array(itemsArray) Else items = itemsArray End If ' التحقق من وجود الملفات قبل الضغط Dim i As Long Dim fullPath As String For i = LBound(items) To UBound(items) ' إذا كان المسار نسبيًا، أضف CurrentProject.Path If InStr(items(i), ":\") = 0 And InStr(items(i), "\\") = 0 Then fullPath = CurrentProject.Path & "\" & items(i) Else fullPath = items(i) End If If Not fso.FileExists(fullPath) And Not fso.FolderExists(fullPath) Then MsgBox "الملف أو المجلد غير موجود: " & fullPath, vbExclamation Exit Sub End If ' تحديث المسار في المصفوفة ليكون مطلقًا items(i) = fullPath Next i Dim archiveProgramPath As String archiveProgramPath = DetermineArchivePath(IIf(Method = WinRAR, "WinRAR", "SevenZip")) If archiveProgramPath = "" Then Exit Sub ' بناء المسار الكامل للأرشيف الناتج Dim archiveFullPath As String Dim baseName As String baseName = fso.GetBaseName(items(LBound(items))) ' استخدام أول عنصر بعد التأكد من المسار archiveFullPath = IIf(targetPath = "", CurrentProject.Path, targetPath) & "\" & _ IIf(archiveName = "", baseName, archiveName) & _ IIf(isSFX, ".exe", GetArchiveExtension(ArchiveType)) Dim Command As String If Method = WinRAR Then Command = """" & archiveProgramPath & """ a -ep1 """ & archiveFullPath & """ " & JoinArchivePaths(items) Command = Command & IIf(password <> "", " -p" & SanitizeInput(password), "") Command = Command & " " & GetWinRARCompressionLevel(compressionLevel) Command = Command & IIf(partSize <> SplitNone, " -v" & GetSplitSizeString(partSize), "") Command = Command & IIf(isSFX, " -sfx", "") Command = Command & IIf(commentFile <> "" And fso.FileExists(commentFile), " -z""" & commentFile & """", "") Command = Command & IIf(deleteOriginals, " -df", "") If ArchiveType = ArchiveXZ Or ArchiveType = ArchiveBZ2 Then MsgBox "WinRAR لا يدعم نوع الأرشيف المحدد: " & ArchiveType, vbExclamation Exit Sub End If ElseIf Method = SevenZip Then Command = """" & archiveProgramPath & """ a """ & archiveFullPath & """ " & JoinArchivePaths(items) Command = Command & IIf(password <> "", " -p" & SanitizeInput(password), "") Command = Command & " " & Get7ZipCompressionLevel(compressionLevel) Command = Command & IIf(partSize <> SplitNone, " -v" & GetSplitSizeString(partSize), "") Command = Command & IIf(isSFX, " -sfx", "") Command = Command & IIf(commentFile <> "" And fso.FileExists(commentFile), " -scc""" & commentFile & """", "") Command = Command & IIf(deleteOriginals, " -sdel", "") Command = Command & " -t" & Get7ZipArchiveType(ArchiveType) End If If Command = "" Then Exit Sub ' تنفيذ الأمر باستخدام ExecuteAndWait مع الانتظار حتى اكتمال العملية ' ExecuteAndWait Command, WindowHidden, True ' Command: السلسلة التي تحتوي على الأمر الكامل (مثل: """C:\Program Files\7-Zip\7z.exe"" a ""C:\output.rar"" ""C:\input.txt""") ' WindowHidden: تحديد نمط النافذة لتكون مخفية (0) أثناء التنفيذ لعدم إظهار واجهة البرنامج ' True: تشغيل الأمر بصلاحيات المسؤول (RunAsAdmin) لضمان الوصول إلى الملفات المحمية إذا لزم الأمر ' تنفيذ الأمر باستخدام ExecuteWithTimeout مع التحكم في المهلة الزمنية ExecuteWithTimeout Command, WindowHidden, 0, True ' Command: السلسلة التي تحتوي على الأمر الكامل (مثل: """C:\Program Files\7-Zip\7z.exe"" x ""C:\archive.rar"" -o""C:\destination""") ' WindowHidden: تحديد نمط النافذة لتكون مخفية (0) أثناء التنفيذ للحفاظ على تجربة مستخدم نظيفة ' 0: المهلة الزمنية بالمللي ثانية (0 تعني الانتظار إلى ما لا نهاية حتى اكتمال العملية) ' True: تشغيل الأمر كمسؤول (RunAsAdmin) If Not IsInLoop Then MsgBox "تم الضغط بنجاح إلى: " & archiveFullPath, vbInformation Else ArchivesList = ArchivesList & archiveFullPath & vbCrLf End If On Error Resume Next If commentFile <> "" And fso.FileExists(commentFile) Then fso.DeleteFile commentFile On Error GoTo 0 Set fso = Nothing Exit Sub ErrorHandler: MsgBox "خطأ في الضغط: " & Err.Description, vbCritical LogError "CompressItems Error: " & Err.Description Set fso = Nothing End Sub ' إجراء لفك ضغط الأرشيفات باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة ' المدخلات: ' - archivePaths: مسار أو مصفوفة مسارات للأرشيفات المراد فك ضغطها ' - destinationPath: مسار الوجهة لفك الضغط ' - password: كلمة المرور لفك تشفير الأرشيف (اختياري، افتراضي: فارغ) ' - Method: أداة فك الضغط (افتراضي: WinRAR) ' - OverwriteMode: وضع الكتابة فوق الملفات الموجودة (افتراضي: OverwriteAll) ' - deleteArchive: حذف الأرشيف بعد فك الضغط (افتراضي: False) ' إجراء لفك ضغط الأرشيفات باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة ' إجراء لفك ضغط الأرشيفات باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة ' إجراء لفك ضغط الأرشيفات باستخدام WinRAR أو 7-Zip بناءً على الخيارات المحددة Sub ExtractItems( _ archivePaths As Variant, _ destinationPath As String, _ Optional ByVal password As String = "", _ Optional ByVal Method As EnumArchiveMethod = WinRAR, _ Optional ByVal OverwriteMode As EnumOverwriteMode = OverwriteAll, _ Optional ByVal deleteArchive As Boolean = False) Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") On Error GoTo ErrorHandler If VarType(archivePaths) = vbEmpty Then MsgBox "لم يتم تحديد أرشيفات!", vbExclamation Exit Sub End If ' تحويل archivePaths إلى مصفوفة إذا كان سلسلة نصية واحدة Dim archives As Variant If Not IsArray(archivePaths) Then archives = Array(archivePaths) Else archives = archivePaths End If ' التحقق من وجود الأرشيفات قبل فك الضغط Dim i As Long Dim fullPath As String For i = LBound(archives) To UBound(archives) ' إذا كان المسار نسبيًا، أضف CurrentProject.Path If InStr(archives(i), ":\") = 0 And InStr(archives(i), "\\") = 0 Then fullPath = CurrentProject.Path & "\" & archives(i) Else fullPath = archives(i) End If If Not fso.FileExists(fullPath) Then MsgBox "الأرشيف غير موجود: " & fullPath, vbExclamation Exit Sub End If ' تحديث المسار في المصفوفة ليكون مطلقًا archives(i) = fullPath Next i ' التحقق من وجود مسار الوجهة وإنشاؤه إذا لم يكن موجودًا If Not fso.FolderExists(destinationPath) Then fso.CreateFolder destinationPath End If Dim archiveProgramPath As String archiveProgramPath = DetermineArchivePath(IIf(Method = WinRAR, "WinRAR", "SevenZip")) If archiveProgramPath = "" Then Exit Sub Dim Command As String If Method = WinRAR Then Command = """" & archiveProgramPath & """ x " & JoinArchivePaths(archives) & " """ & destinationPath & """" Command = Command & IIf(password <> "", " -p" & SanitizeInput(password), "") Command = Command & IIf(OverwriteMode = OverwriteAll, " -o+", IIf(OverwriteMode = OverwritePrompt, "", " -o-")) Command = Command & IIf(deleteArchive, " -df", "") ElseIf Method = SevenZip Then Command = """" & archiveProgramPath & """ x " & JoinArchivePaths(archives) & " -o""" & destinationPath & """" Command = Command & IIf(password <> "", " -p" & SanitizeInput(password), "") Command = Command & IIf(OverwriteMode = OverwriteAll, " -aoa", IIf(OverwriteMode = OverwritePrompt, "", " -aos")) Command = Command & IIf(deleteArchive, " -sdel", "") End If ' تنفيذ الأمر باستخدام ExecuteAndWait مع الانتظار حتى اكتمال العملية ' ExecuteAndWait Command, WindowHidden, True ' Command: السلسلة التي تحتوي على الأمر الكامل (مثل: """C:\Program Files\7-Zip\7z.exe"" a ""C:\output.rar"" ""C:\input.txt""") ' WindowHidden: تحديد نمط النافذة لتكون مخفية (0) أثناء التنفيذ لعدم إظهار واجهة البرنامج ' True: تشغيل الأمر بصلاحيات المسؤول (RunAsAdmin) لضمان الوصول إلى الملفات المحمية إذا لزم الأمر ' تنفيذ الأمر باستخدام ExecuteWithTimeout مع التحكم في المهلة الزمنية ExecuteWithTimeout Command, WindowHidden, 0, True ' Command: السلسلة التي تحتوي على الأمر الكامل (مثل: """C:\Program Files\7-Zip\7z.exe"" x ""C:\archive.rar"" -o""C:\destination""") ' WindowHidden: تحديد نمط النافذة لتكون مخفية (0) أثناء التنفيذ للحفاظ على تجربة مستخدم نظيفة ' 0: المهلة الزمنية بالمللي ثانية (0 تعني الانتظار إلى ما لا نهاية حتى اكتمال العملية) ' True: تشغيل الأمر كمسؤول (RunAsAdmin) If Not IsInLoop Then MsgBox "تم فك الضغط بنجاح إلى: " & destinationPath, vbInformation Else ArchivesList = ArchivesList & destinationPath & vbCrLf End If Set fso = Nothing Exit Sub ErrorHandler: MsgBox "خطأ في فك الضغط: " & Err.Description, vbCritical LogError "ExtractItems Error: " & Err.Description Set fso = Nothing End Sub ' دالة لدمج مسارات الأرشيفات في سلسلة واحدة مع إحاطة كل مسار بعلامات اقتباس ' المدخل: ' - archivePaths: مسار واحد أو مصفوفة من مسارات الأرشيفات ' المخرج: سلسلة نصية تحتوي على المسارات مفصولة بمسافات ومحاطة بعلامات اقتباس (مثل: "path1" "path2") Function JoinArchivePaths(archivePaths As Variant) As String ' تعريف متغير لتخزين النتيجة النهائية Dim Result As String ' متغير للتنقل عبر عناصر المصفوفة Dim p As Variant ' تحويل المدخل إلى مصفوفة إذا لم يكن كذلك لتسهيل المعالجة If Not IsArray(archivePaths) Then archivePaths = Array(archivePaths) ' تكرار على كل مسار في المصفوفة For Each p In archivePaths ' إضافة المسار المنظف إلى النتيجة مع إحاطته بعلامات اقتباس وفاصل مسافة Result = Result & " """ & SanitizeInput(CStr(p)) & """" ' - SanitizeInput: تنظيف المسار من الأحرف غير المرغوبة ' - CStr: تحويل المسار إلى سلسلة نصية Next p ' إرجاع السلسلة الناتجة (بدون مسافة إضافية في البداية) JoinArchivePaths = Result End Function ' إجراء لتسجيل الأخطاء في ملف نصي بمسار المشروع الحالي ' المدخل: ' - errorMessage: رسالة الخطأ المراد تسجيلها Sub LogError(errorMessage As String) ' تعريف مسار ملف السجل (ErrorLog.txt في مسار المشروع الحالي) Dim logFile As String logFile = CurrentProject.Path & "\ErrorLog.txt" ' فتح الملف في وضع الإضافة (Append) برقم قناة #1 Open logFile For Append As #1 ' كتابة التاريخ/الوقت الحالي ورسالة الخطأ في الملف مع فاصل سطر Print #1, Now & " - " & errorMessage ' إغلاق الملف لضمان حفظ التغييرات Close #1 End Sub ' إجراء لعرض نافذة تعليمات بسيطة تحتوي على إرشادات حول استخدام الكود Sub ShowHelp() ' عرض رسالة تحتوي على تعليمات أساسية حول الإجراءات والتعدادات MsgBox "التعليمات:" & vbCrLf & _ "1. CompressItems: لضغط الملفات" & vbCrLf & _ "2. ExtractItems: لفك الضغط" & vbCrLf & _ "3. استخدام التعدادات لتحديد الخيارات" & vbCrLf & _ "راجع التعليقات في الكود للمزيد من التفاصيل", vbInformation ' - vbCrLf: فاصل سطر لتنسيق النص ' - vbInformation: رمز أيقونة المعلومات في نافذة الرسالة End Sub '################################################## '# دوال مساعدة للحلقات (الضغط وفك الضغط) '################################################## ' إجراء لبدء حلقة ضغط متعددة وتهيئة المتغيرات العامة Sub StartCompressionLoop() ' تعيين المتغير العام IsInLoop إلى True للإشارة إلى أن العملية تعمل داخل حلقة IsInLoop = True ' تفعيل وضع الحلقة ' تهيئة المتغير العام ArchivesList كسلسلة فارغة لتخزين قائمة الأرشيفات الناتجة ArchivesList = "" ' تهيئة قائمة الأرشيفات End Sub ' إجراء لعرض رسالة نجاح موحدة بعد انتهاء حلقة الضغط Sub ShowCompressionSuccess() ' التحقق مما إذا كان الإجراء في وضع حلقة وما إذا كانت قائمة الأرشيفات تحتوي على بيانات If IsInLoop And ArchivesList <> "" Then ' عرض رسالة نجاح تحتوي على قائمة الأرشيفات المضغوطة MsgBox "تم الضغط بنجاح للملفات التالية:" & vbCrLf & ArchivesList, vbInformation, "نجاح" ' - vbCrLf: فاصل سطر لتنسيق القائمة ' - vbInformation: رمز أيقونة المعلومات ' - "نجاح": عنوان النافذة End If ' تعطيل وضع الحلقة بعد الانتهاء IsInLoop = False ' إنهاء وضع الحلقة ' إعادة تهيئة قائمة الأرشيفات كسلسلة فارغة للاستخدام المستقبلي ArchivesList = "" ' إعادة تهيئة القائمة End Sub ' إجراء لبدء حلقة فك ضغط متعددة وتهيئة المتغيرات العامة Sub StartExtractionLoop() ' تعيين المتغير العام IsInLoop إلى True للإشارة إلى أن العملية تعمل داخل حلقة IsInLoop = True ' تفعيل وضع الحلقة ' تهيئة المتغير العام ArchivesList كسلسلة فارغة لتخزين قائمة مسارات الوجهة ArchivesList = "" ' تهيئة قائمة الأرشيفات End Sub ' إجراء لعرض رسالة نجاح موحدة بعد انتهاء حلقة فك الضغط Sub ShowExtractionSuccess() ' التحقق مما إذا كان الإجراء في وضع حلقة وما إذا كانت قائمة الأرشيفات تحتوي على بيانات If IsInLoop And ArchivesList <> "" Then ' عرض رسالة نجاح تحتوي على قائمة مسارات الوجهة التي تم فك الضغط إليها MsgBox "تم فك الضغط بنجاح للملفات التالية:" & vbCrLf & ArchivesList, vbInformation, "نجاح" ' - vbCrLf: فاصل سطر لتنسيق القائمة ' - vbInformation: رمز أيقونة المعلومات ' - "نجاح": عنوان النافذة End If ' تعطيل وضع الحلقة بعد الانتهاء IsInLoop = False ' إنهاء وضع الحلقة ' إعادة تهيئة قائمة الأرشيفات كسلسلة فارغة للاستخدام المستقبلي ArchivesList = "" ' إعادة تهيئة القائمة End Sub ' دالة تستخدم لاختبار ' DetermineArchivePath ' التي تحدد مسار ملفي ' ("WinRAR : WinRAR.exe " أو "SevenZip : 7z.exe") ' تلقائيا أو يدوًا ' يمكن حذفها هى فقط كانت لتجربة الكود والتأكد من جلب مسارات التطبيقات Sub TestDetermineArchivePath() ' الغرض: اختبار دالة DetermineArchivePath لتحديد مسارات WinRAR و7-Zip ' المخرجات: ' - طباعة المسارات في نافذة Immediate إذا تم العثور عليها ' - عرض رسالة إذا لم يتم العثور على الأداة On Error GoTo ErrorHandler Dim tools As Variant Dim tool As Variant ' يجب أن يكون Variant لاستخدامه في For Each Dim archivePath As String ' قائمة الأدوات للاختبار tools = Array("WinRAR", "SevenZip") ' اختبار كل أداة For Each tool In tools archivePath = DetermineArchivePath(CStr(tool)) ' تحويل Variant إلى String صراحة If archivePath <> "" Then Debug.Print "تم العثور على " & tool & " في: " & archivePath Else MsgBox "لم يتم العثور على " & tool & ".", vbInformation, "نتيجة الاختبار" End If Next tool Exit Sub ErrorHandler: MsgBox "حدث خطأ أثناء اختبار DetermineArchivePath: " & Err.Description, vbCritical, "خطأ" Exit Sub End Sub الكود مرتبط بـ : ExecuteWith الغرض: تشغيل برنامج والانتظار حتى ينتهي مع السماح بمعالجة الأحداث الأخرى الكود داخل وحده نمطيه عامة باسم : basShellExecutor ' يضمن مقارنة النصوص بناءً على إعدادات قاعدة البيانات (مثل ترتيب الحروف واللغة) Option Compare Database ' يجبر على تعريف المتغيرات صراحة قبل استخدامها، مما يمنع الأخطاء الناتجة عن الأسماء الخاطئة Option Explicit '======================================================================================================================= '------ الثوابت Public Const PROCESS_TIMEOUT_INFINITE As Long = &HFFFFFFFF Public Const PROCESS_STILL_ACTIVE As Long = &H103 Public Const PROCESS_TERMINATED As Long = vbObjectError Or &HDEAD Public Const MAX_PATH_LENGTH As Long = 260 Public Const QS_ALL_INPUT As Long = &H4FF Private Const ERR_NO_COMMAND As Long = vbObjectError Or 1001 Private Const ERR_EXECUTING As Long = vbObjectError Or 1002 Private Const ERR_EXECUTION_FAILED As Long = vbObjectError Or 1003 Private Const ERR_TERMINATION_FAILED As Long = vbObjectError Or 1004 Private Const SHELL_MASK_NOCLOSEPROCESS As Long = &H40 Private Const SHELL_MASK_DOENVSUBST As Long = &H200 Private Const SHELL_MASK_SUPPRESS_ERRORS As Long = &H400 Private Const PROCESS_QUERY_INFO As Long = &H400 Private Const PROCESS_SYNCHRONIZE As Long = &H100000 Private Const PROCESS_TERMINATE As Long = &H1 Private Const ERROR_ACCESS_DENIED As Long = 5 '======================================================================================================================= '------ التعدادات Public Enum ShellWindowStyle WindowHidden = 0 WindowNormal = 1 WindowMinimized = 2 WindowMaximized = 3 WindowNoActivate = 4 End Enum '======================================================================================================================= '------ الأنواع المخصصة #If VBA7 Then Private Type ShellExecuteParams Size As Long Mask As Long ParentWindowHandle As LongPtr Verb As String filePath As String Arguments As String WorkingDirectory As String ShowCommand As Long InstanceHandle As LongPtr ItemListPointer As LongPtr ClassName As String ClassKeyHandle As LongPtr HotKey As Long IconHandle As LongPtr ProcessHandle As LongPtr End Type #Else Private Type ShellExecuteParams Size As Long Mask As Long ParentWindowHandle As Long Verb As String filePath As String Arguments As String WorkingDirectory As String ShowCommand As Long InstanceHandle As Long ItemListPointer As Long ClassName As String ClassKeyHandle As Long HotKey As Long IconHandle As Long ProcessHandle As Long End Type #End If '======================================================================================================================= '------ تعريفات API #If VBA7 Then Private Declare PtrSafe Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As LongPtr ' فتح مقبض العملية Private Declare PtrSafe Function CloseHandle Lib "kernel32.dll" (ByVal hObject As LongPtr) As Long ' إغلاق مقبض العملية Private Declare PtrSafe Function ExpandEnvironmentStringsW Lib "kernel32.dll" (ByVal lpSrc As LongPtr, Optional ByVal lpDst As LongPtr, Optional ByVal nSize As Long) As Long ' توسيع متغيرات البيئة Private Declare PtrSafe Function GetExitCodeProcess Lib "kernel32.dll" (ByVal hProcess As LongPtr, ByRef lpExitCode As Long) As Long ' جلب رمز الخروج للعملية Private Declare PtrSafe Function MsgWaitForMultipleObjects Lib "user32.dll" (ByVal nCount As Long, ByRef pHandles As LongPtr, ByVal bWaitAll As Long, ByVal dwMilliseconds As Long, ByVal dwWakeMask As Long) As Long ' انتظار العمليات مع معالجة الأحداث Private Declare PtrSafe Function SysReAllocStringLen Lib "oleaut32.dll" (ByVal pBSTR As LongPtr, Optional ByVal pszStrPtr As LongPtr, Optional ByVal Length As Long) As Long ' إعادة تخصيص حجم السلسلة Private Declare PtrSafe Function CreateWaitableTimerW Lib "kernel32.dll" (Optional ByVal lpTimerAttributes As LongPtr, Optional ByVal bManualReset As Long, Optional ByVal lpTimerName As LongPtr) As LongPtr ' إنشاء مؤقت قابل للانتظار Private Declare PtrSafe Function GetProcessId Lib "kernel32.dll" (ByVal hProcess As LongPtr) As Long ' جلب معرف العملية Private Declare PtrSafe Function PathCanonicalizeW Lib "shlwapi.dll" (ByVal lpszDst As LongPtr, ByVal lpszSrc As LongPtr) As Long ' تبسيط المسار Private Declare PtrSafe Function PathGetArgsW Lib "shlwapi.dll" (ByVal pszPath As LongPtr) As LongPtr ' استخراج المعاملات من المسار Private Declare PtrSafe Function SetWaitableTimer Lib "kernel32.dll" (ByVal hTimer As LongPtr, ByRef pDueTime As Currency, Optional ByVal lPeriod As Long, Optional ByVal pfnCompletionRoutine As LongPtr, Optional ByVal lpArgToCompletionRoutine As LongPtr, Optional ByVal fResume As Long) As Long ' ضبط المؤقت Private Declare PtrSafe Function ShellExecuteExW Lib "shell32.dll" (ByVal pExecInfo As LongPtr) As Long ' تنفيذ أمر عبر Shell Private Declare PtrSafe Function SysReAllocString Lib "oleaut32.dll" (ByVal pBSTR As LongPtr, Optional ByVal pszStrPtr As LongPtr) As Long ' إعادة تخصيص السلسلة Private Declare PtrSafe Sub PathRemoveArgsW Lib "shlwapi.dll" (ByVal pszPath As LongPtr) ' إزالة المعاملات من المسار Private Declare PtrSafe Function TerminateProcess Lib "kernel32.dll" (ByVal hProcess As LongPtr, ByVal uExitCode As Long) As Long ' إنهاء العملية قسريًا Private Declare PtrSafe Function GetTickCount Lib "kernel32.dll" () As Long ' لقياس الوقت المنقضي #Else Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long ' فتح مقبض العملية Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long ' إغلاق مقبض العملية Private Declare Function ExpandEnvironmentStringsW Lib "kernel32.dll" (ByVal lpSrc As Long, Optional ByVal lpDst As Long, Optional ByVal nSize As Long) As Long ' توسيع متغيرات البيئة Private Declare Function GetExitCodeProcess Lib "kernel32.dll" (ByVal hProcess As Long, ByRef lpExitCode As Long) As Long ' جلب رمز الخروج للعملية Private Declare Function MsgWaitForMultipleObjects Lib "user32.dll" (ByVal nCount As Long, ByRef pHandles As Long, ByVal bWaitAll As Long, ByVal dwMilliseconds As Long, ByVal dwWakeMask As Long) As Long ' انتظار العمليات مع معالجة الأحداث Private Declare Function SysReAllocStringLen Lib "oleaut32.dll" (ByVal pBSTR As Long, Optional ByVal pszStrPtr As Long, Optional ByVal Length As Long) As Long ' إعادة تخصيص حجم السلسلة Private Declare Function CreateWaitableTimerW Lib "kernel32.dll" (Optional ByVal lpTimerAttributes As Long, Optional ByVal bManualReset As Long, Optional ByVal lpTimerName As Long) As Long ' إنشاء مؤقت قابل للانتظار Private Declare Function GetProcessId Lib "kernel32.dll" (ByVal hProcess As Long) As Long ' جلب معرف العملية Private Declare Function PathCanonicalizeW Lib "shlwapi.dll" (ByVal lpszDst As Long, ByVal lpszSrc As Long) As Long ' تبسيط المسار Private Declare Function PathGetArgsW Lib "shlwapi.dll" (ByVal pszPath As Long) As Long ' استخراج المعاملات من المسار Private Declare Function SetWaitableTimer Lib "kernel32.dll" (ByVal hTimer As Long, ByRef pDueTime As Currency, Optional ByVal lPeriod As Long, Optional ByVal pfnCompletionRoutine As Long, Optional ByVal lpArgToCompletionRoutine As Long, Optional ByVal fResume As Long) As Long ' ضبط المؤقت Private Declare Function ShellExecuteExW Lib "shell32.dll" (ByVal pExecInfo As Long) As Long ' تنفيذ أمر عبر Shell Private Declare Function SysReAllocString Lib "oleaut32.dll" (ByVal pBSTR As Long, Optional ByVal pszStrPtr As Long) As Long ' إعادة تخصيص السلسلة Private Declare Sub PathRemoveArgsW Lib "shlwapi.dll" (ByVal pszPath As Long) ' إزالة المعاملات من المسار Private Declare Function TerminateProcess Lib "kernel32.dll" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long ' إنهاء العملية قسريًا Private Declare Function GetTickCount Lib "kernel32.dll" () As Long ' لقياس الوقت المنقضي #End If '======================================================================================================================= '------ المتغيرات العامة و الخاصة Public g_TerminateLoops As Boolean ' متغير للتحكم في إنهاء الحلقات يدويًا Private m_IsExecuting As Boolean ' علامة لمنع التداخل أثناء التنفيذ '======================================================================================================================= '------------------------------------------- الدوال العامة ' تشغيل أمر والانتظار حتى ينتهي مع استجابة الواجهة Public Function ExecuteAndWait(ByVal CommandLine As String, _ Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal, _ Optional ByVal RunAsAdmin As Boolean = False, _ Optional ByVal MaxWaitMs As Long = PROCESS_TIMEOUT_INFINITE) As Long #If VBA7 Then Dim ShellParams As ShellExecuteParams Dim ProcessHandle As LongPtr #Else Dim ShellParams As ShellExecuteParams Dim ProcessHandle As Long #End If Dim ExpandedPath As String Dim Executable As String Dim Arguments As String Dim startTime As Long Dim ExitCode As Long Dim Result As Long If m_IsExecuting Then Err.Raise ERR_EXECUTING, "ExecuteAndWait", "عملية أخرى قيد التنفيذ" End If m_IsExecuting = True On Error GoTo Cleanup ' توسيع متغيرات البيئة ExpandedPath = ExpandEnvVars(CommandLine) ' فصل المسار التنفيذي عن المعاملات يدويًا If Left(ExpandedPath, 1) = """" Then Executable = Mid(ExpandedPath, 2, InStr(2, ExpandedPath, """") - 2) Arguments = Trim(Mid(ExpandedPath, InStr(2, ExpandedPath, """") + 2)) Else Dim Parts() As String Parts = Split(ExpandedPath, " ", 2) Executable = Parts(0) If UBound(Parts) > 0 Then Arguments = Parts(1) Else Arguments = "" End If With ShellParams .Size = LenB(ShellParams) .Mask = SHELL_MASK_NOCLOSEPROCESS Or SHELL_MASK_DOENVSUBST Or SHELL_MASK_SUPPRESS_ERRORS .ShowCommand = WindowStyle .filePath = CanonicalizePath(Executable) ' المسار التنفيذي فقط .Arguments = Arguments ' المعاملات كما هي If RunAsAdmin Then .Verb = "runas" If ShellExecuteExW(VarPtr(ShellParams)) = 0 Then Err.Raise ERR_EXECUTION_FAILED, "ExecuteAndWait", "فشل في تنفيذ الأمر: " & CommandLine End If ProcessHandle = .ProcessHandle End With startTime = GetTickCount Do Result = MsgWaitForMultipleObjects(1, ProcessHandle, False, 100, QS_ALL_INPUT) DoEvents If GetExitCodeProcess(ProcessHandle, ExitCode) Then If ExitCode <> PROCESS_STILL_ACTIVE Then Exit Do End If If MaxWaitMs <> PROCESS_TIMEOUT_INFINITE Then If (GetTickCount - startTime) > MaxWaitMs Then Debug.Print "تجاوز الحد الأقصى للانتظار: " & MaxWaitMs & " ميلي ثانية" Exit Do End If End If Loop ExecuteAndWait = ExitCode Cleanup: If ProcessHandle <> 0 Then CloseHandle ProcessHandle m_IsExecuting = False If Err.Number <> 0 Then Err.Raise Err.Number, "ExecuteAndWait", Err.Description End Function ' دالة لتنفيذ أمر مع مهلة زمنية اختيارية وخيار التشغيل كمسؤول Public Function ExecuteWithTimeout(Command As String, Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal, Optional ByVal TimeoutMs As Long, Optional ByVal RunAsAdmin As Boolean = False, Optional RetryCount As Long = 0) As Long #If VBA7 Then Dim ShellParams As ShellExecuteParams Dim ProcessHandle As LongPtr #Else Dim ShellParams As ShellExecuteParams Dim ProcessHandle As Long #End If Dim ExpandedPath As String Dim Executable As String Dim Arguments As String Dim startTime As Long Dim ExitCode As Long Dim Result As Long Dim RetryIndex As Long If m_IsExecuting Then Err.Raise ERR_EXECUTING, "ExecuteWithTimeout", "عملية أخرى قيد التنفيذ" End If m_IsExecuting = True On Error GoTo Cleanup ExpandedPath = ExpandEnvVars(Command) ' فصل المسار التنفيذي عن المعاملات يدويًا If Left(ExpandedPath, 1) = """" Then Executable = Mid(ExpandedPath, 2, InStr(2, ExpandedPath, """") - 2) Arguments = Trim(Mid(ExpandedPath, InStr(2, ExpandedPath, """") + 2)) Else Dim Parts() As String Parts = Split(ExpandedPath, " ", 2) Executable = Parts(0) If UBound(Parts) > 0 Then Arguments = Parts(1) Else Arguments = "" End If For RetryIndex = 0 To RetryCount With ShellParams .Size = LenB(ShellParams) .Mask = SHELL_MASK_NOCLOSEPROCESS Or SHELL_MASK_DOENVSUBST Or SHELL_MASK_SUPPRESS_ERRORS .ShowCommand = WindowStyle .filePath = CanonicalizePath(Executable) ' المسار التنفيذي فقط .Arguments = Arguments ' المعاملات كما هي If RunAsAdmin Then .Verb = "runas" If ShellExecuteExW(VarPtr(ShellParams)) = 0 Then If RetryIndex = RetryCount Then Err.Raise ERR_EXECUTION_FAILED, "ExecuteWithTimeout", "فشل في تنفيذ الأمر بعد " & RetryCount + 1 & " محاولات: " & Command End If Else ProcessHandle = .ProcessHandle Exit For End If End With Next RetryIndex startTime = GetTickCount Do Result = MsgWaitForMultipleObjects(1, ProcessHandle, False, 100, QS_ALL_INPUT) DoEvents If GetExitCodeProcess(ProcessHandle, ExitCode) Then If ExitCode <> PROCESS_STILL_ACTIVE Then Exit Do End If If TimeoutMs > 0 Then If (GetTickCount - startTime) > TimeoutMs Then If TerminateProcess(ProcessHandle, PROCESS_TERMINATED) = 0 Then Debug.Print "فشل في إنهاء العملية بعد تجاوز المهلة" End If ExitCode = PROCESS_TERMINATED Exit Do End If End If If g_TerminateLoops Then Exit Do Loop ExecuteWithTimeout = ExitCode Cleanup: If ProcessHandle <> 0 Then CloseHandle ProcessHandle m_IsExecuting = False If Err.Number <> 0 Then Err.Raise Err.Number, "ExecuteWithTimeout", Err.Description End Function ' دالة لتشغيل أمر باستخدام WScript.Shell مع خيار الانتظار Public Function ExecuteWScript(ByVal CommandLine As String, Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal, Optional ByVal WaitForCompletion As Boolean = False) As Long Dim WScriptShell As Object On Error GoTo ErrorHandler Set WScriptShell = CreateObject("WScript.Shell") ExecuteWScript = WScriptShell.Run(CommandLine, WindowStyle, WaitForCompletion) Exit Function ErrorHandler: Debug.Print "خطأ في تشغيل الأمر عبر WScript: " & Err.Description Err.Raise Err.Number, "ExecuteWScript", "خطأ في تشغيل الأمر عبر WScript: " & Err.Description End Function ' دالة محسنة لتشغيل أمر باستخدام WScript.Shell والتقاط الناتج Public Function ExecuteWScriptCapture(ByVal CommandLine As String, Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal) As String Dim WScriptShell As Object Dim ShellExec As Object Dim Output As String On Error GoTo ErrorHandler Set WScriptShell = CreateObject("WScript.Shell") Set ShellExec = WScriptShell.Exec(CommandLine) Do While ShellExec.Status = 0 DoEvents Loop Output = ShellExec.StdOut.ReadAll ExecuteWScriptCapture = Output Exit Function ErrorHandler: Debug.Print "خطأ في تشغيل الأمر عبر WScript: " & Err.Description ExecuteWScriptCapture = "" Err.Raise Err.Number, "ExecuteWScriptCapture", "خطأ في تشغيل الأمر عبر WScript: " & Err.Description End Function '======================================================================================================================= '------ الدوال المساعدة ' دالة لتوسيع متغيرات البيئة في سلسلة (مثل %windir%) Private Function ExpandEnvVars(ByVal Path As String) As String Dim Buffer As String Dim Length As Long If InStr(Path, "%") Then Length = ExpandEnvironmentStringsW(StrPtr(Path), 0, 0) If Length > 0 Then Buffer = String$(Length - 1, vbNullChar) If ExpandEnvironmentStringsW(StrPtr(Path), StrPtr(Buffer), Length) Then ExpandEnvVars = Left$(Buffer, Length - 1) Else Debug.Print "فشل توسيع متغيرات البيئة، يتم إرجاع المسار الأصلي: " & Path ExpandEnvVars = Path End If Else ExpandEnvVars = Path End If Else ExpandEnvVars = Path End If End Function ' دالة لتبسيط المسار (مثل حل النقاط . و ..) Private Function CanonicalizePath(ByVal Path As String) As String Dim TempPath As String If InStr(Path, "\.") Or InStr(Path, ".\") Then If Len(Path) < MAX_PATH_LENGTH Then TempPath = String$(MAX_PATH_LENGTH - 1, vbNullChar) If PathCanonicalizeW(StrPtr(TempPath), StrPtr(Path)) Then CanonicalizePath = Left$(TempPath, InStr(TempPath, vbNullChar) - 1) Else Debug.Print "فشل تبسيط المسار، يتم إرجاع المسار الأصلي: " & Path CanonicalizePath = Path End If Else CanonicalizePath = Path End If Else CanonicalizePath = Path End If End Function ' دالة لاستخراج المعاملات من المسار Private Function ExtractArguments(ByRef Path As String) As String SysReAllocString VarPtr(ExtractArguments), PathGetArgsW(StrPtr(Path)) If LenB(ExtractArguments) Then PathRemoveArgsW StrPtr(Path) If InStr(ExtractArguments, """") Then ExtractArguments = Replace(ExtractArguments, """", """""") End If End Function ' دالة مساعدة لاستخراج اسم العملية من الأمر Private Function ExtractProcessName(ByVal CommandLine As String) As String Dim Parts() As String Dim FirstPart As String If Left(CommandLine, 1) = """" Then FirstPart = Mid(CommandLine, 2, InStr(2, CommandLine, """") - 2) Else Parts = Split(CommandLine, " ") FirstPart = Parts(0) End If ExtractProcessName = Mid(FirstPart, InStrRev(FirstPart, "\") + 1) End Function ' دالة لإنهاء عملية باستخدام WMI بناءً على اسم العملية Public Function KillProcess(sProcessName As String, Optional sHost As String = ".") As Boolean On Error GoTo Error_Handler Dim oWMI As Object Dim sWMIQuery As String Dim oCols As Object Dim oCol As Object Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sHost & "\root\cimv2") sWMIQuery = "SELECT Name FROM Win32_Process" Set oCols = oWMI.ExecQuery(sWMIQuery) For Each oCol In oCols If LCase(sProcessName) = LCase(oCol.Name) Then oCol.Terminate End If Next oCol KillProcess = True Error_Handler_Exit: On Error Resume Next Set oCol = Nothing Set oCols = Nothing Set oWMI = Nothing Exit Function Error_Handler: Debug.Print "خطأ في KillProcess: " & Err.Description & " - رقم الخطأ: " & Err.Number KillProcess = False Resume Error_Handler_Exit End Function اوامر الاستدعاء المختلفة : سوف نقوم بعمل وحده نمطيه عامه لتجربة : WinRAR اسم الوحده النمطيه : basArchiveExamplesWinRAR ' يضمن مقارنة النصوص بناءً على إعدادات قاعدة البيانات (مثل ترتيب الحروف واللغة) Option Compare Database ' يجبر على تعريف المتغيرات صراحة قبل استخدامها، مما يمنع الأخطاء الناتجة عن الأسماء الخاطئة Option Explicit ' وحدة نمطية تحتوي على أمثلة شاملة لضغط وفك ضغط باستخدام WinRAR مع كل الخيارات ' =========================================================================== ' 1. ضغط ملف واحد ' =========================================================================== ' بدون كلمة مرور، مستوى ضغط عادي Sub CompressSingleFileNoPasswordWinRAR() CompressItems "file1.txt", , WinRAR, ArchiveZIP, CompressionNormal ' الناتج: file1.rar في CurrentProject.Path End Sub ' مع كلمة مرور، مستوى ضغط أقصى Sub CompressSingleFileWithPasswordMaxCompressionWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems "file1.txt", password, WinRAR, ArchiveZIP, CompressionMaximum ' الناتج: file1.rar (مشفر، مضغوط بأقصى مستوى) في CurrentProject.Path End Sub ' مع تقسيم الأرشيف (Split500MB) Sub CompressSingleFileWithSplitWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems "file1.txt", password, WinRAR, ArchiveRAR, CompressionNormal, Split500MB ' الناتج: file1.rar مقسم إلى أجزاء بحجم 500 ميجابايت End Sub ' ذاتي الاستخراج (SFX) مع تعليق ' ضغط مجلد واحد مع تعليق باستخدام متغير لكلمة المرور Sub CompressSingleFileSFXWithCommentWinRAR() Dim commentLines As Variant Dim commentFile As String Dim password As String ' تعيين كلمة المرور password = "officena" ' إعداد التعليق باستخدام المتغير commentLines = Array( _ "منتديات أوفيسنا", _ "www.officena.net", _ "وقت وتاريخ إنشاء الأرشيف:", _ Format(Now, "dd-mm-yyyy hh:nn AM/PM"), _ "كلمة المرور لفك الضغط: " & password, _ "مع أطيب الأماني: أبو جودى") commentFile = CreateCommentFile(commentLines) ' استخدام كلمة المرور في الضغط CompressItems "Folder1", password, WinRAR, ArchiveRAR, CompressionNormal, , , , True, commentFile ' الناتج: Folder1.rar (مشفر بكلمة المرور "MS-Access(officena)"، مع تعليق) في CurrentProject.Path End Sub ' =========================================================================== ' 2. فك ضغط ملف واحد ' =========================================================================== ' بدون كلمة مرور، الكتابة فوق الملفات Sub ExtractSingleFileNoPasswordOverwriteWinRAR() ExtractItems CurrentProject.Path & "\file1.zip", CurrentProject.Path & "\Extracted", , WinRAR, OverwriteAll ' الناتج: محتويات file1.rar مفكوكة في CurrentProject.Path\Extracted مع الكتابة فوق الملفات End Sub ' مع كلمة مرور، تجاهل الملفات الموجودة Sub ExtractSingleFileWithPasswordNoOverwriteWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" ExtractItems CurrentProject.Path & "\file1.zip", CurrentProject.Path & "\Extracted", password, WinRAR, OverwriteNone ' الناتج: محتويات file1.rar مفكوكة في CurrentProject.Path\Extracted مع تجاهل الملفات الموجودة End Sub ' =========================================================================== ' 3. ضغط عدة ملفات (كل ملف على حدة) ' =========================================================================== ' بدون كلمة مرور، نوع ZIP Sub CompressMultipleFilesSeparateNoPasswordZipWinRAR() Dim filesArray As Variant filesArray = Array(CurrentProject.Path & "\file1.txt", CurrentProject.Path & "\file2.docx", CurrentProject.Path & "\file3.pdf") StartCompressionLoop Dim filePath As Variant For Each filePath In filesArray CompressItems CStr(filePath), , WinRAR, ArchiveZIP, CompressionNormal Next filePath ShowCompressionSuccess ' الناتج: file1.zip, file2.zip, file3.zip في CurrentProject.Path End Sub ' مع كلمة مرور وتعليق Sub CompressMultipleFilesSeparateWithCommentWinRAR() Dim commentLines As Variant Dim commentFile As String Dim password As String ' تعيين كلمة المرور password = "officena" ' إعداد التعليق باستخدام المتغير commentLines = Array( _ "منتديات أوفيسنا", _ "www.officena.net", _ "وقت وتاريخ إنشاء الأرشيف:", _ Format(Now, "dd-mm-yyyy hh:nn AM/PM"), _ "كلمة المرور لفك الضغط: " & password, _ "مع أطيب الأماني: أبو جودى") commentFile = CreateCommentFile(commentLines) Dim filesArray As Variant filesArray = Array("file1.txt", "file2.docx", "file3.pdf", "Folder1", "Folder2") StartCompressionLoop Dim filePath As Variant For Each filePath In filesArray CompressItems CStr(filePath), password, WinRAR, ArchiveRAR, CompressionNormal, , , , , commentFile Next filePath ShowCompressionSuccess ' الناتج: file1.rar, file2.rar, file3.rar (مشفرة، مع تعليق) في CurrentProject.Path End Sub ' =========================================================================== ' 4. فك ضغط عدة ملفات (كل ملف على حدة) ' =========================================================================== ' بدون كلمة مرور Sub ExtractMultipleFilesSeparateNoPasswordWinRAR() Dim filesArray As Variant filesArray = Array(CurrentProject.Path & "\file1.rar", CurrentProject.Path & "\file2.rar", CurrentProject.Path & "\file3.rar") StartExtractionLoop Dim filePath As Variant For Each filePath In filesArray ExtractItems CStr(filePath), CurrentProject.Path, , WinRAR, OverwriteAll Next filePath ShowExtractionSuccess ' الناتج: محتويات كل ملف مفكوكة في CurrentProject.Path End Sub ' مع كلمة مرور Sub ExtractMultipleFilesSeparateWithPasswordWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" Dim filesArray As Variant filesArray = Array(CurrentProject.Path & "\file1.rar", CurrentProject.Path & "\file2.rar", CurrentProject.Path & "\file3.rar") StartExtractionLoop Dim filePath As Variant For Each filePath In filesArray ExtractItems CStr(filePath), CurrentProject.Path, password, WinRAR, OverwriteNone Next filePath ShowExtractionSuccess ' الناتج: محتويات كل ملف مفكوكة في CurrentProject.Path مع تجاهل الموجود End Sub ' =========================================================================== ' 5. ضغط عدة ملفات في أرشيف واحد ' =========================================================================== ' بدون كلمة مرور، تقسيم 100MB Sub CompressMultipleFilesOneArchiveWithSplitWinRAR() Dim files As Variant files = Array("file1.txt", "file2.docx", "file3.pdf") CompressItems files, , WinRAR, ArchiveRAR, CompressionNormal, Split100MB, , "CompressedFiles" ' الناتج: CompressedFiles.rar مقسم إلى أجزاء بحجم 100 ميجابايت End Sub ' مع كلمة مرور وتعليق Sub CompressMultipleFilesOneArchiveWithCommentWinRAR() Dim commentLines As Variant Dim commentFile As String Dim password As String ' تعيين كلمة المرور password = "officena" ' إعداد التعليق باستخدام المتغير commentLines = Array( _ "منتديات أوفيسنا", _ "www.officena.net", _ "وقت وتاريخ إنشاء الأرشيف:", _ Format(Now, "dd-mm-yyyy hh:nn AM/PM"), _ "كلمة المرور لفك الضغط: " & password, _ "مع أطيب الأماني: أبو جودى") commentFile = CreateCommentFile(commentLines) Dim files As Variant files = Array("file1.txt", "file2.docx", "file3.pdf") CompressItems files, password, WinRAR, ArchiveRAR, CompressionMaximum, , , "CompressedFiles", , commentFile ' الناتج: CompressedFiles.rar (مشفر، مع تعليق) في CurrentProject.Path End Sub ' =========================================================================== ' 6. فك ضغط أرشيف واحد يحتوي على عدة ملفات ' =========================================================================== ' بدون كلمة مرور Sub ExtractMultipleFilesOneArchiveNoPasswordWinRAR() Dim archives As Variant archives = Array(CurrentProject.Path & "\CompressedFiles.rar") ExtractItems archives, CurrentProject.Path, , WinRAR, OverwriteAll ' الناتج: محتويات CompressedFiles.rar مفكوكة في CurrentProject.Path End Sub ' مع كلمة مرور Sub ExtractMultipleFilesOneArchiveWithPasswordWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" Dim archives As Variant archives = Array(CurrentProject.Path & "\CompressedFiles.rar") ExtractItems archives, CurrentProject.Path, password, WinRAR, OverwriteNone ' الناتج: محتويات CompressedFiles.rar مفكوكة في CurrentProject.Path مع تجاهل الموجود End Sub ' =========================================================================== ' 7. ضغط مجلد واحد ' =========================================================================== ' مع تعليق Sub CompressSingleFolderWithCommentWinRAR() Dim commentLines As Variant Dim password As String ' تعيين كلمة المرور password = "officena" ' إعداد التعليق باستخدام المتغير commentLines = Array( _ "منتديات أوفيسنا", _ "www.officena.net", _ "وقت وتاريخ إنشاء الأرشيف:", _ Format(Now, "dd-mm-yyyy hh:nn AM/PM"), _ "كلمة المرور لفك الضغط: " & password, _ "مع أطيب الأماني: أبو جودى") Dim commentFile As String commentFile = CreateCommentFile(commentLines) CompressItems CurrentProject.Path & "\Folder1", password, WinRAR, ArchiveRAR, CompressionNormal, , , , , commentFile ' الناتج: Folder1.rar (مشفر، مع تعليق) في CurrentProject.Path End Sub ' مع تقسيم وSFX Sub CompressSingleFolderWithSplitSFXWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems CurrentProject.Path & "\Folder1", password, WinRAR, ArchiveRAR, CompressionNormal, Split1GB, , "Folder1SFX", True ' الناتج: Folder1SFX.exe مقسم إلى أجزاء بحجم 1 جيجابايت End Sub ' =========================================================================== ' 8. ضغط عدة مجلدات (كل مجلد على حدة) ' =========================================================================== ' بدون كلمة مرور Sub CompressMultipleFoldersNoPasswordWinRAR() Dim foldersArray As Variant foldersArray = Array(CurrentProject.Path & "\Folder1", CurrentProject.Path & "\Folder2") StartCompressionLoop Dim folderPath As Variant For Each folderPath In foldersArray CompressItems CStr(folderPath), , WinRAR, ArchiveRAR, CompressionNormal Next folderPath ShowCompressionSuccess ' الناتج: Folder1.rar, Folder2.rar في CurrentProject.Path End Sub ' مع كلمة مرور وتعليق Sub CompressMultipleFoldersWithCommentWinRAR() Dim commentLines As Variant Dim password As String ' تعيين كلمة المرور password = "officena" ' إعداد التعليق باستخدام المتغير commentLines = Array( _ "منتديات أوفيسنا", _ "www.officena.net", _ "وقت وتاريخ إنشاء الأرشيف:", _ Format(Now, "dd-mm-yyyy hh:nn AM/PM"), _ "كلمة المرور لفك الضغط: " & password, _ "مع أطيب الأماني: أبو جودى") Dim commentFile As String commentFile = CreateCommentFile(commentLines) Dim foldersArray As Variant foldersArray = Array(CurrentProject.Path & "\Folder1", CurrentProject.Path & "\Folder2") StartCompressionLoop Dim folderPath As Variant For Each folderPath In foldersArray CompressItems CStr(folderPath), password, WinRAR, ArchiveRAR, CompressionNormal, , , , , commentFile Next folderPath ShowCompressionSuccess ' الناتج: Folder1.rar, Folder2.rar (مشفرة، مع تعليق) في CurrentProject.Path End Sub ' =========================================================================== ' 9. فك ضغط مجلد واحد ' =========================================================================== ' بدون كلمة مرور Sub ExtractSingleFolderNoPasswordWinRAR() ExtractItems CurrentProject.Path & "\Folder1.rar", CurrentProject.Path & "\Extracted", , WinRAR, OverwriteAll ' الناتج: محتويات Folder1.rar مفكوكة في CurrentProject.Path\Extracted End Sub ' مع كلمة مرور Sub ExtractSingleFolderWithPasswordWinRAR() Dim password As String ' تعيين كلمة المرور password = "officena" ExtractItems CurrentProject.Path & "\Folder1.rar", CurrentProject.Path & "\Extracted", password, WinRAR, OverwriteNone ' الناتج: محتويات Folder1.rar مفكوكة في CurrentProject.Path\Extracted مع تجاهل الموجود End Sub سوف نقوم بعمل وحده نمطيه عامه لتجربة : 7Zip اسم الوحده النمطيه : basArchiveExamples7Zip ' يضمن مقارنة النصوص بناءً على إعدادات قاعدة البيانات (مثل ترتيب الحروف واللغة) Option Compare Database ' يجبر على تعريف المتغيرات صراحة قبل استخدامها، مما يمنع الأخطاء الناتجة عن الأسماء الخاطئة Option Explicit ' وحدة نمطية تحتوي على أمثلة شاملة لضغط وفك ضغط باستخدام 7-Zip مع كل الخيارات ' =========================================================================== ' 1. ضغط ملف واحد ' =========================================================================== ' بدون كلمة مرور، مستوى ضغط عادي Sub CompressSingleFileNoPasswordSevenZip() CompressItems "file1.txt", , SevenZip, Archive7z, CompressionNormal ' الناتج: file1.7z في CurrentProject.Path End Sub ' مع كلمة مرور، مستوى ضغط أقصى Sub CompressSingleFileWithPasswordMaxCompressionSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems "file1.txt", password, SevenZip, Archive7z, CompressionMaximum ' الناتج: file1.7z (مشفر، مضغوط بأقصى مستوى) في CurrentProject.Path End Sub ' مع تقسيم الأرشيف (Split500MB) Sub CompressSingleFileWithSplitSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems "file1.txt", password, SevenZip, Archive7z, CompressionNormal, Split500MB ' الناتج: file1.7z مقسم إلى أجزاء بحجم 500 ميجابايت End Sub ' ذاتي الاستخراج (SFX) Sub CompressSingleFileSFXSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems "file1.txt", password, SevenZip, Archive7z, CompressionNormal, , , "File1SFX", True ' الناتج: File1SFX.exe (مشفر) في CurrentProject.Path End Sub ' =========================================================================== ' 2. فك ضغط ملف واحد ' =========================================================================== ' بدون كلمة مرور، الكتابة فوق الملفات Sub ExtractSingleFileNoPasswordOverwriteSevenZip() ExtractItems CurrentProject.Path & "\file1.7z", CurrentProject.Path & "\Extracted", , SevenZip, OverwriteAll ' الناتج: محتويات file1.7z مفكوكة في CurrentProject.Path\Extracted مع الكتابة فوق الملفات End Sub ' مع كلمة مرور، تجاهل الملفات الموجودة Sub ExtractSingleFileWithPasswordNoOverwriteSevenZip() ExtractItems CurrentProject.Path & "\file1.7z", CurrentProject.Path & "\Extracted", "MyPassword123", SevenZip, OverwriteNone ' الناتج: محتويات file1.7z مفكوكة في CurrentProject.Path\Extracted مع تجاهل الملفات الموجودة End Sub ' =========================================================================== ' 3. ضغط عدة ملفات (كل ملف على حدة) ' =========================================================================== ' بدون كلمة مرور Sub CompressMultipleFilesSeparateNoPasswordSevenZip() Dim filesArray As Variant filesArray = Array("file1.txt", CurrentProject.Path & "\file2.docx", CurrentProject.Path & "\file3.pdf") StartCompressionLoop Dim filePath As Variant For Each filePath In filesArray CompressItems CStr(filePath), , SevenZip, Archive7z, CompressionNormal Next filePath ShowCompressionSuccess ' الناتج: file1.7z, file2.7z, file3.7z في CurrentProject.Path End Sub ' مع كلمة مرور وتقسيم Sub CompressMultipleFilesSeparateWithSplitSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" Dim filesArray As Variant filesArray = Array(CurrentProject.Path & "\file1.txt", CurrentProject.Path & "\file2.docx", CurrentProject.Path & "\file3.pdf") StartCompressionLoop Dim filePath As Variant For Each filePath In filesArray CompressItems CStr(filePath), password, SevenZip, Archive7z, CompressionNormal, Split100MB Next filePath ShowCompressionSuccess ' الناتج: file1.7z, file2.7z, file3.7z مقسمة إلى أجزاء بحجم 100 ميجابايت End Sub ' =========================================================================== ' 4. فك ضغط عدة ملفات (كل ملف على حدة) ' =========================================================================== ' بدون كلمة مرور Sub ExtractMultipleFilesSeparateNoPasswordSevenZip() Dim filesArray As Variant filesArray = Array(CurrentProject.Path & "\file1.7z", CurrentProject.Path & "\file2.7z", CurrentProject.Path & "\file3.7z") StartExtractionLoop Dim filePath As Variant For Each filePath In filesArray ExtractItems CStr(filePath), CurrentProject.Path, , SevenZip, OverwriteAll Next filePath ShowExtractionSuccess ' الناتج: محتويات كل ملف مفكوكة في CurrentProject.Path End Sub ' مع كلمة مرور Sub ExtractMultipleFilesSeparateWithPasswordSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" Dim filesArray As Variant filesArray = Array(CurrentProject.Path & "\file1.7z", CurrentProject.Path & "\file2.7z", CurrentProject.Path & "\file3.7z") StartExtractionLoop Dim filePath As Variant For Each filePath In filesArray ExtractItems CStr(filePath), CurrentProject.Path, password, SevenZip, OverwriteNone Next filePath ShowExtractionSuccess ' الناتج: محتويات كل ملف مفكوكة في CurrentProject.Path مع تجاهل الموجود End Sub ' =========================================================================== ' 5. ضغط عدة ملفات في أرشيف واحد ' =========================================================================== ' بدون كلمة مرور، تقسيم 100MB Sub CompressMultipleFilesOneArchiveWithSplitSevenZip() Dim files As Variant files = Array("file1.txt", "file2.docx", "file3.pdf") CompressItems files, , SevenZip, Archive7z, CompressionNormal, Split100MB, , "CompressedFiles" ' الناتج: CompressedFiles.7z مقسم إلى أجزاء بحجم 100 ميجابايت End Sub ' مع كلمة مرور وSFX Sub CompressMultipleFilesOneArchiveSFXSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" Dim files As Variant files = Array("file1.txt", "file2.docx", "file3.pdf") CompressItems files, password, SevenZip, Archive7z, CompressionMaximum, , , "CompressedFilesSFX", True ' الناتج: CompressedFilesSFX.exe (مشفر) في CurrentProject.Path End Sub ' =========================================================================== ' 6. فك ضغط أرشيف واحد يحتوي على عدة ملفات ' =========================================================================== ' بدون كلمة مرور Sub ExtractMultipleFilesOneArchiveNoPasswordSevenZip() Dim archives As Variant archives = Array(CurrentProject.Path & "\CompressedFiles.7z") ExtractItems archives, CurrentProject.Path, , SevenZip, OverwriteAll ' الناتج: محتويات CompressedFiles.7z مفكوكة في CurrentProject.Path End Sub ' مع كلمة مرور Sub ExtractMultipleFilesOneArchiveWithPasswordSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" Dim archives As Variant archives = Array(CurrentProject.Path & "\CompressedFiles.7z") ExtractItems archives, CurrentProject.Path, password, SevenZip, OverwriteNone ' الناتج: محتويات CompressedFiles.7z مفكوكة في CurrentProject.Path مع تجاهل الموجود End Sub ' =========================================================================== ' 7. ضغط مجلد واحد ' =========================================================================== ' مع تقسيم وSFX Sub CompressSingleFolderWithSplitSFXSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" CompressItems CurrentProject.Path & "\Folder1", password, SevenZip, Archive7z, CompressionNormal, Split1GB, , "Folder1SFX", True ' الناتج: Folder1SFX.exe مقسم إلى أجزاء بحجم 1 جيجابايت End Sub ' =========================================================================== ' 8. ضغط عدة مجلدات (كل مجلد على حدة) ' =========================================================================== ' بدون كلمة مرور Sub CompressMultipleFoldersNoPasswordSevenZip() Dim foldersArray As Variant foldersArray = Array(CurrentProject.Path & "\Folder1", CurrentProject.Path & "\Folder2") StartCompressionLoop Dim folderPath As Variant For Each folderPath In foldersArray CompressItems CStr(folderPath), , SevenZip, Archive7z, CompressionNormal Next folderPath ShowCompressionSuccess ' الناتج: Folder1.7z, Folder2.7z في CurrentProject.Path End Sub ' مع كلمة مرور وتقسيم Sub CompressMultipleFoldersWithSplitSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" Dim foldersArray As Variant foldersArray = Array(CurrentProject.Path & "\Folder1", CurrentProject.Path & "\Folder2") StartCompressionLoop Dim folderPath As Variant For Each folderPath In foldersArray CompressItems CStr(folderPath), password, SevenZip, Archive7z, CompressionNormal, Split500MB Next folderPath ShowCompressionSuccess ' الناتج: Folder1.7z, Folder2.7z مقسمة إلى أجزاء بحجم 500 ميجابايت End Sub ' =========================================================================== ' 9. فك ضغط مجلد واحد ' =========================================================================== ' بدون كلمة مرور Sub ExtractSingleFolderNoPasswordSevenZip() ExtractItems CurrentProject.Path & "\Folder1.7z", CurrentProject.Path & "\Extracted", , SevenZip, OverwriteAll ' الناتج: محتويات Folder1.7z مفكوكة في CurrentProject.Path\Extracted End Sub ' مع كلمة مرور Sub ExtractSingleFolderWithPasswordSevenZip() Dim password As String ' تعيين كلمة المرور password = "officena" ExtractItems CurrentProject.Path & "\Folder1.7z", CurrentProject.Path & "\Extracted", password, SevenZip, OverwriteNone ' الناتج: محتويات Folder1.7z مفكوكة في CurrentProject.Path\Extracted مع تجاهل الموجود End Sub وأخيــــر وحده نمطيه عامة لضغط قاعدة البيانات الحاليه( الأمامية أو الخلفيه أو الأمامية والخلفية معا أو القاعدة الحاليه فقط ان لم تكن منقسمه ) اسم الوحدة النمطية : basCompressDatabase الكود ' يضمن مقارنة النصوص بناءً على إعدادات قاعدة البيانات (مثل ترتيب الحروف واللغة) Option Compare Database ' يجبر على تعريف المتغيرات صراحة قبل استخدامها، مما يمنع الأخطاء الناتجة عن الأسماء الخاطئة Option Explicit ' تعداد لتحديد نوع القاعدة المراد ضغطها Enum EnumDatabaseType FrontEndOnly = 0 ' ضغط القاعدة الحالية (Front-End) فقط BackEndOnly = 1 ' ضغط القاعدة الخلفية (Back-End) فقط BothFrontAndBack = 2 ' ضغط القاعدة الحالية والخلفية معًا End Enum ' دالة لضغط قاعدة البيانات الحالية و/أو الخلفية بناءً على الخيارات ' المدخلات: ' - dbType: نوع القاعدة المراد ضغطها (Front-End، Back-End، أو الاثنين) ' - archiveName: اسم الأرشيف الناتج (اختياري، لو فارغ بيستخدم اسم القاعدة) ' - targetPath: مسار حفظ الأرشيف (اختياري، لو فارغ بيستخدم مسار القاعدة) ' - Method: أداة الضغط (WinRAR أو SevenZip، افتراضي SevenZip) ' - ArchiveType: نوع الأرشيف (افتراضي Archive7z) ' - compressionLevel: مستوى الضغط (افتراضي CompressionNormal) ' - password: كلمة المرور لتشفير الأرشيف (اختياري) ' - commentFile: مسار ملف التعليقات لإضافته إلى الأرشيف (اختياري) ' دالة لضغط قاعدة البيانات الحالية و/أو الخلفية بناءً على الخيارات ' المدخلات: ' - dbType: نوع القاعدة المراد ضغطها (Front-End، Back-End، أو الاثنين) ' - archiveName: اسم الأرشيف الناتج (اختياري، لو فارغ بيستخدم اسم القاعدة) ' - targetPath: مسار حفظ الأرشيف (اختياري، لو فارغ بيستخدم مسار القاعدة) ' - Method: أداة الضغط (WinRAR أو SevenZip، افتراضي SevenZip) ' - ArchiveType: نوع الأرشيف (افتراضي Archive7z) ' - compressionLevel: مستوى الضغط (افتراضي CompressionNormal) ' - password: كلمة المرور لتشفير الأرشيف (اختياري) ' - commentFile: مسار ملف التعليقات لإضافته إلى الأرشيف (اختياري) ' - showHelp: عرض تعليمات قبل الضغط إذا كان True (افتراضي False) ' دالة لضغط قاعدة البيانات الحالية و/أو الخلفية بناءً على الخيارات ' المدخلات: ' - dbType: نوع القاعدة المراد ضغطها (إجباري: FrontEndOnly, BackEndOnly, BothFrontAndBack) ' - archiveName: اسم الأرشيف الناتج (اختياري، لو فارغ بيستخدم اسم القاعدة) ' - targetPath: مسار حفظ الأرشيف (اختياري، لو فارغ بيستخدم مسار القاعدة) ' - Method: أداة الضغط (اختياري: WinRAR أو SevenZip، افتراضي SevenZip) ' - ArchiveType: نوع الأرشيف (اختياري، افتراضي Archive7z) ' - compressionLevel: مستوى الضغط (اختياري، افتراضي CompressionNormal) ' - password: كلمة المرور لتشفير الأرشيف (اختياري) ' - commentFile: مسار ملف التعليقات لإضافته إلى الأرشيف (اختياري) Sub CompressDatabase( _ ByVal dbType As EnumDatabaseType, _ Optional ByVal archiveName As String = "", _ Optional ByVal targetPath As String = "", _ Optional ByVal Method As EnumArchiveMethod = SevenZip, _ Optional ByVal ArchiveType As EnumArchiveType = Archive7z, _ Optional ByVal compressionLevel As EnumCompressionLevel = CompressionNormal, _ Optional ByVal password As String = "", _ Optional ByVal commentFile As String = "") Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") On Error GoTo ErrorHandler ' التحقق من صحة dbType If dbType < FrontEndOnly Or dbType > BothFrontAndBack Then MsgBox "خطأ: نوع القاعدة (dbType) غير صحيح!", vbExclamation ShowHelp Exit Sub End If ' متغيرات لتخزين مسارات القاعدة Dim frontEndPath As String Dim backEndPath As String Dim tempFrontEndPath As String Dim tempBackEndPath As String ' الحصول على مسار القاعدة الحالية (Front-End) frontEndPath = CurrentDb.Name ' مثل: "C:\Users\YourUser\Documents\FrontEnd.accdb" ' الحصول على مسار القاعدة الخلفية (Back-End) إذا كانت موجودة backEndPath = GetBackEndPath() ' تحديد المسارات المؤقتة في مجلد Temp tempFrontEndPath = Environ$("TEMP") & "\" & fso.GetFileName(frontEndPath) If backEndPath <> "" Then tempBackEndPath = Environ$("TEMP") & "\" & fso.GetFileName(backEndPath) End If ' تحديد مسار واسم الأرشيف الناتج Dim finalTargetPath As String finalTargetPath = IIf(targetPath = "", fso.GetParentFolderName(frontEndPath), targetPath) ' معالجة حسب نوع القاعدة المطلوب Select Case dbType Case FrontEndOnly ' ضغط القاعدة الحالية فقط fso.CopyFile frontEndPath, tempFrontEndPath, True Dim frontEndArchiveName As String frontEndArchiveName = IIf(archiveName = "", fso.GetBaseName(frontEndPath), archiveName) & GetArchiveExtension(ArchiveType) Dim uniqueFrontEndArchive As String uniqueFrontEndArchive = GenerateUniqueFileName(finalTargetPath, frontEndArchiveName) CompressItems tempFrontEndPath, password, Method, ArchiveType, compressionLevel, SplitNone, finalTargetPath, fso.GetBaseName(uniqueFrontEndArchive), , commentFile If fso.FileExists(tempFrontEndPath) Then fso.DeleteFile tempFrontEndPath Case BackEndOnly ' ضغط القاعدة الخلفية فقط If backEndPath = "" Then MsgBox "لا توجد قاعدة خلفية مرتبطة!", vbExclamation Exit Sub End If fso.CopyFile backEndPath, tempBackEndPath, True Dim backEndArchiveName As String backEndArchiveName = IIf(archiveName = "", fso.GetBaseName(backEndPath), archiveName) & GetArchiveExtension(ArchiveType) Dim uniqueBackEndArchive As String uniqueBackEndArchive = GenerateUniqueFileName(finalTargetPath, backEndArchiveName) CompressItems tempBackEndPath, password, Method, ArchiveType, compressionLevel, SplitNone, finalTargetPath, fso.GetBaseName(uniqueBackEndArchive), , commentFile If fso.FileExists(tempBackEndPath) Then fso.DeleteFile tempBackEndPath Case BothFrontAndBack ' ضغط القاعدتين معًا If backEndPath = "" Then MsgBox "لا توجد قاعدة خلفية، سيتم ضغط القاعدة الحالية فقط!", vbInformation fso.CopyFile frontEndPath, tempFrontEndPath, True Dim singleArchiveName As String singleArchiveName = IIf(archiveName = "", fso.GetBaseName(frontEndPath) & "_Full", archiveName) & GetArchiveExtension(ArchiveType) Dim uniqueSingleArchive As String uniqueSingleArchive = GenerateUniqueFileName(finalTargetPath, singleArchiveName) CompressItems tempFrontEndPath, password, Method, ArchiveType, compressionLevel, SplitNone, finalTargetPath, fso.GetBaseName(uniqueSingleArchive), , commentFile If fso.FileExists(tempFrontEndPath) Then fso.DeleteFile tempFrontEndPath Else fso.CopyFile frontEndPath, tempFrontEndPath, True fso.CopyFile backEndPath, tempBackEndPath, True Dim bothFiles(1) As String bothFiles(0) = tempFrontEndPath bothFiles(1) = tempBackEndPath Dim bothArchiveName As String bothArchiveName = IIf(archiveName = "", fso.GetBaseName(frontEndPath) & "_Full", archiveName) & GetArchiveExtension(ArchiveType) Dim uniqueBothArchive As String uniqueBothArchive = GenerateUniqueFileName(finalTargetPath, bothArchiveName) CompressItems bothFiles, password, Method, ArchiveType, compressionLevel, SplitNone, finalTargetPath, fso.GetBaseName(uniqueBothArchive), , commentFile If fso.FileExists(tempFrontEndPath) Then fso.DeleteFile tempFrontEndPath If fso.FileExists(tempBackEndPath) Then fso.DeleteFile tempBackEndPath End If End Select Set fso = Nothing Exit Sub ErrorHandler: MsgBox "خطأ في ضغط قاعدة البيانات: " & Err.Description, vbCritical LogError "CompressDatabase Error: " & Err.Description ShowHelp ' عرض التعليمات عند حدوث أي خطأ ' تنظيف الملفات المؤقتة في حالة الخطأ If fso.FileExists(tempFrontEndPath) Then fso.DeleteFile tempFrontEndPath If fso.FileExists(tempBackEndPath) Then fso.DeleteFile tempBackEndPath Set fso = Nothing End Sub ' دالة مساعدة للحصول على مسار القاعدة الخلفية من الجداول المرتبطة Private Function GetBackEndPath() As String On Error GoTo ErrorHandler Dim tdf As DAO.TableDef Dim db As DAO.Database Set db = CurrentDb ' فحص الجداول المرتبطة For Each tdf In db.TableDefs If Len(tdf.Connect) > 0 Then ' إذا كان الجدول مرتبطًا ' استخراج المسار من خاصية Connect Dim connectString As String connectString = tdf.Connect If InStr(connectString, "DATABASE=") > 0 Then GetBackEndPath = Mid(connectString, InStr(connectString, "DATABASE=") + 9) Exit Function End If End If Next tdf ' إذا لم يتم العثور على قاعدة خلفية GetBackEndPath = "" Exit Function ErrorHandler: GetBackEndPath = "" End Function ' توليد اسم ملف فريد Public Function GenerateUniqueFileName(Folderpath As String, Filename As String) As String Dim baseName As String Dim extension As String Dim counter As Integer Dim uniqueName As String baseName = Left(Filename, InStrRev(Filename, ".") - 1) extension = Mid(Filename, InStrRev(Filename, ".")) uniqueName = Folderpath & "\" & Filename counter = 1 Do While Dir(uniqueName) <> "" uniqueName = Folderpath & "\" & baseName & " (" & counter & ")" & extension counter = counter + 1 Loop GenerateUniqueFileName = uniqueName End Function ' إجراء لتسجيل الأخطاء في ملف نصي بمسار المشروع الحالي Sub LogError(errorMessage As String) Dim logFile As String logFile = CurrentProject.Path & "\ErrorLog.txt" Open logFile For Append As #1 Print #1, Now & " - " & errorMessage Close #1 End Sub ' إجراء لعرض نافذة تعليمات تحتوي على تعريف الباراميترات Sub ShowHelp() MsgBox "تعليمات CompressDatabase:" & vbCrLf & _ "الباراميترات:" & vbCrLf & _ "- dbType (إجباري): نوع القاعدة المراد ضغطها" & vbCrLf & _ " * FrontEndOnly: ضغط القاعدة الحالية فقط" & vbCrLf & _ " * BackEndOnly: ضغط القاعدة الخلفية فقط" & vbCrLf & _ " * BothFrontAndBack: ضغط القاعدتين معًا" & vbCrLf & _ "- archiveName (اختياري): اسم الأرشيف، لو فارغ يستخدم اسم القاعدة" & vbCrLf & _ "- targetPath (اختياري): مسار الحفظ، لو فارغ يستخدم مسار القاعدة" & vbCrLf & _ "- Method (اختياري): أداة الضغط (WinRAR أو SevenZip)، افتراضي SevenZip" & vbCrLf & _ "- ArchiveType (اختياري): نوع الأرشيف (مثل Archive7z, ArchiveZIP)، افتراضي Archive7z" & vbCrLf & _ "- compressionLevel (اختياري): مستوى الضغط (مثل CompressionNormal)، افتراضي CompressionNormal" & vbCrLf & _ "- password (اختياري): كلمة المرور للتشفير" & vbCrLf & _ "- commentFile (اختياري): مسار ملف التعليقات" & vbCrLf & _ "ملاحظات: راجع التعدادات (EnumDatabaseType, EnumArchiveMethod, EnumArchiveType, EnumCompressionLevel) في الكود", vbInformation End Sub Sub TestCompressDatabase() Dim commentLines As Variant Dim commentFile As String Dim password As String ' تعيين كلمة المرور password = "officena" ' إعداد التعليق باستخدام المتغير commentLines = Array( _ "منتديات أوفيسنا", _ "www.officena.net", _ "وقت وتاريخ إنشاء الأرشيف:", _ Format(Now, "dd-mm-yyyy hh:nn AM/PM"), _ "كلمة المرور لفك الضغط: " & password, _ "مع أطيب الأماني: أبو جودى") commentFile = CreateCommentFile(commentLines) ' ضغط القاعدة الحالية فقط CompressDatabase FrontEndOnly, , , WinRAR, ArchiveZIP, CompressionMaximum, password, commentFile '' ' ضغط القاعدة الخلفية فقط (لو موجودة) '' CompressDatabase BackEndOnly, "MyBackend", "", WinRAR, ArchiveRAR '' ' الناتج: C:\Backups\MyBackend.zip '' '' ' ضغط القاعدتين معًا '' CompressDatabase BothFrontAndBack, "FullBackup", "", WinRAR, ArchiveRAR, CompressionMaximum '' ' الناتج: C:\Backups\FullBackup.7z يحتوي على الـ Front-End والـ Back-End (لو موجود) End Sub فى انتظار آرائكم بشغف انا كتبت اكواد التجربة على اعتبار وجود المجلدات والملفات فى مسار قاعدة البيانات على ان يكون اسماء المجلدات كالتالى : Folder1 Folder2 واسماء الملفات كالتالى : file1.txt file2.docx file3.pdf طبعا يمكنكم تغيير اسماء وأماكن المجلدات والمسارات فى اكواد التجربه كما يحلو لكم ولكن قد أكون أخطأت فى أى شئ بسبب كبر الكود وتشعبه لذلك فى انتظار مراجعتكم وآرائكم ان شاء الله التحديثات الأخيــــره فى حالة التعامل مع البرامج المحموله امكانيه تحديد مسار التطبيق مره واحده فقط طوال الجلسة الحاليه اضافة نسخ محمولة مختلفة الانويه فى مسار القاعدة ل 7-zip ودعم الكود للعمل من خلالهما مباشرة فى حالة عدم التسطيب دعم اضافى لانواع الارشيف المختلفه والتعامل مع الانواع بمرونه اكبر اضافة وظائف لضغط قاعدة البيانات الحلفيه سواء كانت امامية فقط أو امامية وخلفيه لكل واحده على حده او كلاهما معا مع اسم فريد للاحتفاظ بالنسخ القديمه المضغوطة بتعداد متزايد اتمنى لكم تجربة ممتعة وأخيـــــــــــرا المرفق كلمة مرور فك الضغط للمرفق : officena OfficenaZip V2.zip
- 14 replies
-
- 2
-
-
- ms access
- microsoft access
-
(و42 أكثر)
موسوم بكلمه :
- ms access
- microsoft access
- ميكروسوفت
- ميكروسوفت اكسس
- الاكسس
- قسم الاكسس
- منتديات أوفيسنا
- منتديات اوفيسنا
- اوفيسنا
- أوفيسنا
- ابو جودي
- ابو جودى
- ابوجودى
- ابو جوى
- شخابيط ابو جودى
- شخابيط وافكار
- شخابيط وأفكار
- شخابيط
- الضغط وفك الضغط
- winrar
- seven zip
- 7zip
- 7-zip
- rar
- ضغط ملفات
- ضغط مجلدات
- ضغط تقرير
- ضفط تقارير
- sfx
- أرشيفات ذاتية الاستخراج
- أرشيف
- ارشيف
- 7z
- zip
- ضغط المستندات
- مشاركة الملفات
- تبسيط عمليات النسخ الاحتياطي
- عمليات النسخ الاحتياطي أو الأرشفة
- archiveutility
- archive
- هدية
- هديه
- ضغط وفك الضغط للملفات والمجلدات
- وين رار
-
السلام عليكم ورحمة الله وبركاته أشارك معكم اليوم وحدة نمطية متقدمة باسم basShellExecutor تهدف إلى توفير حلول مرنة وفعالة لتنفيذ الأوامر والملفات في بيئة Windows مع تحكم دقيق بالعمليات تم تصميم هذه الوحدة لتلبية احتياجات المطورين المختلفة والمتنوعة وتعرف او شائعه لدى المطورين باسم : ShellWait ولكن تم اعادة هيكلة وتطوير الوظائف بشكل احترافى لاضفاء أكبر قدر ممكن من الفاعليه والمرونة والكفائه وتعدد الاستخدمات ودعم تنوع الخيارات الممكنه بقدر الإمكان مميزات الكود المرونة: يدعم تنفيذ الأوامر بثلاث طرق (انتظار غير محدود , مهلة زمنية محددة , تنفيذ بسيط) مما يجعله متعدد الاستخدامات الاستجابة: يستخدم " DoEvents " لضمان استجابة واجهة المستخدم أثناء الانتظار مما يمنع تجمد التطبيق التحكم الدقيق: يتيح إنهاء الحلقات يدويا عبر متغير عام (g_TerminateLoops) ويمنع التداخل بين الاستدعاءات باستخدام (m_IsExecuting) التوافق: توافق تعريفات API مع أنظمة 32 بت و64 بت معالجة الأخطاء: يوفر معالجة أخطاء قوية مع رسائل واضحة لتسهيل التصحيح التنظيم: مقسم إلى أقسام واضحة (ثوابت , تعريفات , دوال) مع تعليقات عربية شاملة لتسهيل الصيانة والفهم وظيفة الكود تتيح وحدة basShellExecutor تشغيل الأوامر والملفات بثلاث طرق مختلفة مع القدرة على التحكم في وقت التنفيذ و معالجة الأحداث والتقاط النتائج الدوال الرئيسية هي: ExecuteAndWait: الغرض: تنفيذ أمر أو تشغيل ملف والانتظار حتى اكتماله مع استجابة مستمرة لواجهة المستخدم الاستخدام: مثالي للعمليات التي تحتاج إلى إكمال كامل قبل المتابعة (مثل فتح برنامج وانتظار إغلاقه) ExecuteWithTimeout: الغرض: تنفيذ أمر أو تشغيل ملف مع مهلة زمنية مع إمكانية إنهاء العملية إذا تجاوزت الحد الاستخدام: ممناسب للعمليات ذات الوقت المحدود أو التي قد تتوقف (مثل محاولة استخدام أدوات خارجية) ExecuteWScript: الغرض: تنفيذ أمر بسيط باستخدام " WScript.Shell " مع خيار الانتظار الاستخدام: مفيد للمهام السريعة دون تعقيد على سبيل المثال (مثل تشغيل أوامر CMD) ExecuteWScriptCapture (اختياري): الغرض: تنفيذ أمر والتقاط ناتجه النصي للاستخدام البرمجي الاستخدام: مثالي لتحليل نتائج الأوامر (مثل قوائم الملفات من " dir " ) اسم الوحدة النمطية العامة : basShellExecutor الكود : ' يضمن مقارنة النصوص بناءً على إعدادات قاعدة البيانات (مثل ترتيب الحروف واللغة) Option Compare Database ' يجبر على تعريف المتغيرات صراحة قبل استخدامها، مما يمنع الأخطاء الناتجة عن الأسماء الخاطئة Option Explicit '======================================================================================================================= '------ الثوابت Public Const PROCESS_TIMEOUT_INFINITE As Long = &HFFFFFFFF Public Const PROCESS_STILL_ACTIVE As Long = &H103 Public Const PROCESS_TERMINATED As Long = vbObjectError Or &HDEAD Public Const MAX_PATH_LENGTH As Long = 260 Public Const QS_ALL_INPUT As Long = &H4FF Private Const ERR_NO_COMMAND As Long = vbObjectError Or 1001 Private Const ERR_EXECUTING As Long = vbObjectError Or 1002 Private Const ERR_EXECUTION_FAILED As Long = vbObjectError Or 1003 Private Const ERR_TERMINATION_FAILED As Long = vbObjectError Or 1004 Private Const SHELL_MASK_NOCLOSEPROCESS As Long = &H40 Private Const SHELL_MASK_DOENVSUBST As Long = &H200 Private Const SHELL_MASK_SUPPRESS_ERRORS As Long = &H400 Private Const PROCESS_QUERY_INFO As Long = &H400 Private Const PROCESS_SYNCHRONIZE As Long = &H100000 Private Const PROCESS_TERMINATE As Long = &H1 Private Const ERROR_ACCESS_DENIED As Long = 5 '======================================================================================================================= '------ التعدادات Public Enum ShellWindowStyle WindowHidden = 0 WindowNormal = 1 WindowMinimized = 2 WindowMaximized = 3 WindowNoActivate = 4 End Enum '======================================================================================================================= '------ الأنواع المخصصة #If VBA7 Then Private Type ShellExecuteParams Size As Long Mask As Long ParentWindowHandle As LongPtr Verb As String filePath As String Arguments As String WorkingDirectory As String ShowCommand As Long InstanceHandle As LongPtr ItemListPointer As LongPtr ClassName As String ClassKeyHandle As LongPtr HotKey As Long IconHandle As LongPtr ProcessHandle As LongPtr End Type #Else Private Type ShellExecuteParams Size As Long Mask As Long ParentWindowHandle As Long Verb As String filePath As String Arguments As String WorkingDirectory As String ShowCommand As Long InstanceHandle As Long ItemListPointer As Long ClassName As String ClassKeyHandle As Long HotKey As Long IconHandle As Long ProcessHandle As Long End Type #End If '======================================================================================================================= '------ تعريفات API #If VBA7 Then Private Declare PtrSafe Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As LongPtr ' فتح مقبض العملية Private Declare PtrSafe Function CloseHandle Lib "kernel32.dll" (ByVal hObject As LongPtr) As Long ' إغلاق مقبض العملية Private Declare PtrSafe Function ExpandEnvironmentStringsW Lib "kernel32.dll" (ByVal lpSrc As LongPtr, Optional ByVal lpDst As LongPtr, Optional ByVal nSize As Long) As Long ' توسيع متغيرات البيئة Private Declare PtrSafe Function GetExitCodeProcess Lib "kernel32.dll" (ByVal hProcess As LongPtr, ByRef lpExitCode As Long) As Long ' جلب رمز الخروج للعملية Private Declare PtrSafe Function MsgWaitForMultipleObjects Lib "user32.dll" (ByVal nCount As Long, ByRef pHandles As LongPtr, ByVal bWaitAll As Long, ByVal dwMilliseconds As Long, ByVal dwWakeMask As Long) As Long ' انتظار العمليات مع معالجة الأحداث Private Declare PtrSafe Function SysReAllocStringLen Lib "oleaut32.dll" (ByVal pBSTR As LongPtr, Optional ByVal pszStrPtr As LongPtr, Optional ByVal Length As Long) As Long ' إعادة تخصيص حجم السلسلة Private Declare PtrSafe Function CreateWaitableTimerW Lib "kernel32.dll" (Optional ByVal lpTimerAttributes As LongPtr, Optional ByVal bManualReset As Long, Optional ByVal lpTimerName As LongPtr) As LongPtr ' إنشاء مؤقت قابل للانتظار Private Declare PtrSafe Function GetProcessId Lib "kernel32.dll" (ByVal hProcess As LongPtr) As Long ' جلب معرف العملية Private Declare PtrSafe Function PathCanonicalizeW Lib "shlwapi.dll" (ByVal lpszDst As LongPtr, ByVal lpszSrc As LongPtr) As Long ' تبسيط المسار Private Declare PtrSafe Function PathGetArgsW Lib "shlwapi.dll" (ByVal pszPath As LongPtr) As LongPtr ' استخراج المعاملات من المسار Private Declare PtrSafe Function SetWaitableTimer Lib "kernel32.dll" (ByVal hTimer As LongPtr, ByRef pDueTime As Currency, Optional ByVal lPeriod As Long, Optional ByVal pfnCompletionRoutine As LongPtr, Optional ByVal lpArgToCompletionRoutine As LongPtr, Optional ByVal fResume As Long) As Long ' ضبط المؤقت Private Declare PtrSafe Function ShellExecuteExW Lib "shell32.dll" (ByVal pExecInfo As LongPtr) As Long ' تنفيذ أمر عبر Shell Private Declare PtrSafe Function SysReAllocString Lib "oleaut32.dll" (ByVal pBSTR As LongPtr, Optional ByVal pszStrPtr As LongPtr) As Long ' إعادة تخصيص السلسلة Private Declare PtrSafe Sub PathRemoveArgsW Lib "shlwapi.dll" (ByVal pszPath As LongPtr) ' إزالة المعاملات من المسار Private Declare PtrSafe Function TerminateProcess Lib "kernel32.dll" (ByVal hProcess As LongPtr, ByVal uExitCode As Long) As Long ' إنهاء العملية قسريًا Private Declare PtrSafe Function GetTickCount Lib "kernel32.dll" () As Long ' لقياس الوقت المنقضي #Else Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long ' فتح مقبض العملية Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long ' إغلاق مقبض العملية Private Declare Function ExpandEnvironmentStringsW Lib "kernel32.dll" (ByVal lpSrc As Long, Optional ByVal lpDst As Long, Optional ByVal nSize As Long) As Long ' توسيع متغيرات البيئة Private Declare Function GetExitCodeProcess Lib "kernel32.dll" (ByVal hProcess As Long, ByRef lpExitCode As Long) As Long ' جلب رمز الخروج للعملية Private Declare Function MsgWaitForMultipleObjects Lib "user32.dll" (ByVal nCount As Long, ByRef pHandles As Long, ByVal bWaitAll As Long, ByVal dwMilliseconds As Long, ByVal dwWakeMask As Long) As Long ' انتظار العمليات مع معالجة الأحداث Private Declare Function SysReAllocStringLen Lib "oleaut32.dll" (ByVal pBSTR As Long, Optional ByVal pszStrPtr As Long, Optional ByVal Length As Long) As Long ' إعادة تخصيص حجم السلسلة Private Declare Function CreateWaitableTimerW Lib "kernel32.dll" (Optional ByVal lpTimerAttributes As Long, Optional ByVal bManualReset As Long, Optional ByVal lpTimerName As Long) As Long ' إنشاء مؤقت قابل للانتظار Private Declare Function GetProcessId Lib "kernel32.dll" (ByVal hProcess As Long) As Long ' جلب معرف العملية Private Declare Function PathCanonicalizeW Lib "shlwapi.dll" (ByVal lpszDst As Long, ByVal lpszSrc As Long) As Long ' تبسيط المسار Private Declare Function PathGetArgsW Lib "shlwapi.dll" (ByVal pszPath As Long) As Long ' استخراج المعاملات من المسار Private Declare Function SetWaitableTimer Lib "kernel32.dll" (ByVal hTimer As Long, ByRef pDueTime As Currency, Optional ByVal lPeriod As Long, Optional ByVal pfnCompletionRoutine As Long, Optional ByVal lpArgToCompletionRoutine As Long, Optional ByVal fResume As Long) As Long ' ضبط المؤقت Private Declare Function ShellExecuteExW Lib "shell32.dll" (ByVal pExecInfo As Long) As Long ' تنفيذ أمر عبر Shell Private Declare Function SysReAllocString Lib "oleaut32.dll" (ByVal pBSTR As Long, Optional ByVal pszStrPtr As Long) As Long ' إعادة تخصيص السلسلة Private Declare Sub PathRemoveArgsW Lib "shlwapi.dll" (ByVal pszPath As Long) ' إزالة المعاملات من المسار Private Declare Function TerminateProcess Lib "kernel32.dll" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long ' إنهاء العملية قسريًا Private Declare Function GetTickCount Lib "kernel32.dll" () As Long ' لقياس الوقت المنقضي #End If '======================================================================================================================= '------ المتغيرات العامة و الخاصة Public g_TerminateLoops As Boolean ' متغير للتحكم في إنهاء الحلقات يدويًا Private m_IsExecuting As Boolean ' علامة لمنع التداخل أثناء التنفيذ '======================================================================================================================= '------------------------------------------- الدوال العامة ' تشغيل أمر والانتظار حتى ينتهي مع استجابة الواجهة Public Function ExecuteAndWait(ByVal CommandLine As String, _ Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal, _ Optional ByVal RunAsAdmin As Boolean = False, _ Optional ByVal MaxWaitMs As Long = PROCESS_TIMEOUT_INFINITE) As Long #If VBA7 Then Dim ShellParams As ShellExecuteParams Dim ProcessHandle As LongPtr #Else Dim ShellParams As ShellExecuteParams Dim ProcessHandle As Long #End If Dim ExpandedPath As String Dim Executable As String Dim Arguments As String Dim startTime As Long Dim ExitCode As Long Dim Result As Long If m_IsExecuting Then Err.Raise ERR_EXECUTING, "ExecuteAndWait", "عملية أخرى قيد التنفيذ" End If m_IsExecuting = True On Error GoTo Cleanup ' توسيع متغيرات البيئة ExpandedPath = ExpandEnvVars(CommandLine) ' فصل المسار التنفيذي عن المعاملات يدويًا If Left(ExpandedPath, 1) = """" Then Executable = Mid(ExpandedPath, 2, InStr(2, ExpandedPath, """") - 2) Arguments = Trim(Mid(ExpandedPath, InStr(2, ExpandedPath, """") + 2)) Else Dim Parts() As String Parts = Split(ExpandedPath, " ", 2) Executable = Parts(0) If UBound(Parts) > 0 Then Arguments = Parts(1) Else Arguments = "" End If With ShellParams .Size = LenB(ShellParams) .Mask = SHELL_MASK_NOCLOSEPROCESS Or SHELL_MASK_DOENVSUBST Or SHELL_MASK_SUPPRESS_ERRORS .ShowCommand = WindowStyle .filePath = CanonicalizePath(Executable) ' المسار التنفيذي فقط .Arguments = Arguments ' المعاملات كما هي If RunAsAdmin Then .Verb = "runas" If ShellExecuteExW(VarPtr(ShellParams)) = 0 Then Err.Raise ERR_EXECUTION_FAILED, "ExecuteAndWait", "فشل في تنفيذ الأمر: " & CommandLine End If ProcessHandle = .ProcessHandle End With startTime = GetTickCount Do Result = MsgWaitForMultipleObjects(1, ProcessHandle, False, 100, QS_ALL_INPUT) DoEvents If GetExitCodeProcess(ProcessHandle, ExitCode) Then If ExitCode <> PROCESS_STILL_ACTIVE Then Exit Do End If If MaxWaitMs <> PROCESS_TIMEOUT_INFINITE Then If (GetTickCount - startTime) > MaxWaitMs Then Debug.Print "تجاوز الحد الأقصى للانتظار: " & MaxWaitMs & " ميلي ثانية" Exit Do End If End If Loop ExecuteAndWait = ExitCode Cleanup: If ProcessHandle <> 0 Then CloseHandle ProcessHandle m_IsExecuting = False If Err.Number <> 0 Then Err.Raise Err.Number, "ExecuteAndWait", Err.Description End Function ' دالة لتنفيذ أمر مع مهلة زمنية اختيارية وخيار التشغيل كمسؤول Public Function ExecuteWithTimeout(Command As String, Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal, Optional ByVal TimeoutMs As Long, Optional ByVal RunAsAdmin As Boolean = False, Optional RetryCount As Long = 0) As Long #If VBA7 Then Dim ShellParams As ShellExecuteParams Dim ProcessHandle As LongPtr #Else Dim ShellParams As ShellExecuteParams Dim ProcessHandle As Long #End If Dim ExpandedPath As String Dim Executable As String Dim Arguments As String Dim startTime As Long Dim ExitCode As Long Dim Result As Long Dim RetryIndex As Long If m_IsExecuting Then Err.Raise ERR_EXECUTING, "ExecuteWithTimeout", "عملية أخرى قيد التنفيذ" End If m_IsExecuting = True On Error GoTo Cleanup ExpandedPath = ExpandEnvVars(Command) ' فصل المسار التنفيذي عن المعاملات يدويًا If Left(ExpandedPath, 1) = """" Then Executable = Mid(ExpandedPath, 2, InStr(2, ExpandedPath, """") - 2) Arguments = Trim(Mid(ExpandedPath, InStr(2, ExpandedPath, """") + 2)) Else Dim Parts() As String Parts = Split(ExpandedPath, " ", 2) Executable = Parts(0) If UBound(Parts) > 0 Then Arguments = Parts(1) Else Arguments = "" End If For RetryIndex = 0 To RetryCount With ShellParams .Size = LenB(ShellParams) .Mask = SHELL_MASK_NOCLOSEPROCESS Or SHELL_MASK_DOENVSUBST Or SHELL_MASK_SUPPRESS_ERRORS .ShowCommand = WindowStyle .filePath = CanonicalizePath(Executable) ' المسار التنفيذي فقط .Arguments = Arguments ' المعاملات كما هي If RunAsAdmin Then .Verb = "runas" If ShellExecuteExW(VarPtr(ShellParams)) = 0 Then If RetryIndex = RetryCount Then Err.Raise ERR_EXECUTION_FAILED, "ExecuteWithTimeout", "فشل في تنفيذ الأمر بعد " & RetryCount + 1 & " محاولات: " & Command End If Else ProcessHandle = .ProcessHandle Exit For End If End With Next RetryIndex startTime = GetTickCount Do Result = MsgWaitForMultipleObjects(1, ProcessHandle, False, 100, QS_ALL_INPUT) DoEvents If GetExitCodeProcess(ProcessHandle, ExitCode) Then If ExitCode <> PROCESS_STILL_ACTIVE Then Exit Do End If If TimeoutMs > 0 Then If (GetTickCount - startTime) > TimeoutMs Then If TerminateProcess(ProcessHandle, PROCESS_TERMINATED) = 0 Then Debug.Print "فشل في إنهاء العملية بعد تجاوز المهلة" End If ExitCode = PROCESS_TERMINATED Exit Do End If End If If g_TerminateLoops Then Exit Do Loop ExecuteWithTimeout = ExitCode Cleanup: If ProcessHandle <> 0 Then CloseHandle ProcessHandle m_IsExecuting = False If Err.Number <> 0 Then Err.Raise Err.Number, "ExecuteWithTimeout", Err.Description End Function ' دالة لتشغيل أمر باستخدام WScript.Shell مع خيار الانتظار Public Function ExecuteWScript(ByVal CommandLine As String, Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal, Optional ByVal WaitForCompletion As Boolean = False) As Long Dim WScriptShell As Object On Error GoTo ErrorHandler Set WScriptShell = CreateObject("WScript.Shell") ExecuteWScript = WScriptShell.Run(CommandLine, WindowStyle, WaitForCompletion) Exit Function ErrorHandler: Debug.Print "خطأ في تشغيل الأمر عبر WScript: " & Err.Description Err.Raise Err.Number, "ExecuteWScript", "خطأ في تشغيل الأمر عبر WScript: " & Err.Description End Function ' دالة محسنة لتشغيل أمر باستخدام WScript.Shell والتقاط الناتج Public Function ExecuteWScriptCapture(ByVal CommandLine As String, Optional ByVal WindowStyle As ShellWindowStyle = WindowNormal) As String Dim WScriptShell As Object Dim ShellExec As Object Dim Output As String On Error GoTo ErrorHandler Set WScriptShell = CreateObject("WScript.Shell") Set ShellExec = WScriptShell.Exec(CommandLine) Do While ShellExec.Status = 0 DoEvents Loop Output = ShellExec.StdOut.ReadAll ExecuteWScriptCapture = Output Exit Function ErrorHandler: Debug.Print "خطأ في تشغيل الأمر عبر WScript: " & Err.Description ExecuteWScriptCapture = "" Err.Raise Err.Number, "ExecuteWScriptCapture", "خطأ في تشغيل الأمر عبر WScript: " & Err.Description End Function '======================================================================================================================= '------ الدوال المساعدة ' دالة لتوسيع متغيرات البيئة في سلسلة (مثل %windir%) Private Function ExpandEnvVars(ByVal Path As String) As String Dim Buffer As String Dim Length As Long If InStr(Path, "%") Then Length = ExpandEnvironmentStringsW(StrPtr(Path), 0, 0) If Length > 0 Then Buffer = String$(Length - 1, vbNullChar) If ExpandEnvironmentStringsW(StrPtr(Path), StrPtr(Buffer), Length) Then ExpandEnvVars = Left$(Buffer, Length - 1) Else Debug.Print "فشل توسيع متغيرات البيئة، يتم إرجاع المسار الأصلي: " & Path ExpandEnvVars = Path End If Else ExpandEnvVars = Path End If Else ExpandEnvVars = Path End If End Function ' دالة لتبسيط المسار (مثل حل النقاط . و ..) Private Function CanonicalizePath(ByVal Path As String) As String Dim TempPath As String If InStr(Path, "\.") Or InStr(Path, ".\") Then If Len(Path) < MAX_PATH_LENGTH Then TempPath = String$(MAX_PATH_LENGTH - 1, vbNullChar) If PathCanonicalizeW(StrPtr(TempPath), StrPtr(Path)) Then CanonicalizePath = Left$(TempPath, InStr(TempPath, vbNullChar) - 1) Else Debug.Print "فشل تبسيط المسار، يتم إرجاع المسار الأصلي: " & Path CanonicalizePath = Path End If Else CanonicalizePath = Path End If Else CanonicalizePath = Path End If End Function ' دالة لاستخراج المعاملات من المسار Private Function ExtractArguments(ByRef Path As String) As String SysReAllocString VarPtr(ExtractArguments), PathGetArgsW(StrPtr(Path)) If LenB(ExtractArguments) Then PathRemoveArgsW StrPtr(Path) If InStr(ExtractArguments, """") Then ExtractArguments = Replace(ExtractArguments, """", """""") End If End Function ' دالة مساعدة لاستخراج اسم العملية من الأمر Private Function ExtractProcessName(ByVal CommandLine As String) As String Dim Parts() As String Dim FirstPart As String If Left(CommandLine, 1) = """" Then FirstPart = Mid(CommandLine, 2, InStr(2, CommandLine, """") - 2) Else Parts = Split(CommandLine, " ") FirstPart = Parts(0) End If ExtractProcessName = Mid(FirstPart, InStrRev(FirstPart, "\") + 1) End Function ' دالة لإنهاء عملية باستخدام WMI بناءً على اسم العملية Public Function KillProcess(sProcessName As String, Optional sHost As String = ".") As Boolean On Error GoTo Error_Handler Dim oWMI As Object Dim sWMIQuery As String Dim oCols As Object Dim oCol As Object Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sHost & "\root\cimv2") sWMIQuery = "SELECT Name FROM Win32_Process" Set oCols = oWMI.ExecQuery(sWMIQuery) For Each oCol In oCols If LCase(sProcessName) = LCase(oCol.Name) Then oCol.Terminate End If Next oCol KillProcess = True Error_Handler_Exit: On Error Resume Next Set oCol = Nothing Set oCols = Nothing Set oWMI = Nothing Exit Function Error_Handler: Debug.Print "خطأ في KillProcess: " & Err.Description & " - رقم الخطأ: " & Err.Number KillProcess = False Resume Error_Handler_Exit End Function وأخيــــرا الامثلة : '======================================================================================================================= '------ أمثلة الاستدعاء ' مثال لاستدعاء ExecuteAndWait ' يفتح Notepad وينتظر إغلاقه Sub TestExecuteAndWait() Dim ExitCode As Long On Error Resume Next ExitCode = ExecuteAndWait("notepad.exe C:\test.txt", WindowNormal) Err.Clear ' مسح أي أخطاء سابقة If Err.Number = 0 Then MsgBox "رمز الخروج: " & ExitCode Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub ' مثال لاستدعاء ExecuteWithTimeout ' يفتح الحاسبة وينتظر 5 ثوانٍ كحد أقصى Sub TestExecuteWithTimeout() Dim ProcessId As Long On Error Resume Next ProcessId = ExecuteWithTimeout("paint.exe", WindowMaximized, 5000) Err.Clear ' مسح أي أخطاء سابقة If Err.Number = PROCESS_TERMINATED Then MsgBox "اكتملت العملية برمز الخروج: " & ProcessId ElseIf Err.Number = 0 Then MsgBox "معرف العملية: " & ProcessId & " (انتهت المهلة)" Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub ' مثال لاستدعاء ExecuteWScript ' يشغل أمر dir في CMD وينتظر النتيجة Sub TestExecuteWScript() Dim Result As Long On Error Resume Next Result = ExecuteWScript("cmd.exe /c dir", WindowNormal, True) Err.Clear ' مسح أي أخطاء سابقة If Err.Number = 0 Then MsgBox "النتيجة: " & Result Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub ' مثال لاستدعاء ExecuteWScript مع إبقاء النافذة مفتوحة Sub TestExecuteWScript_KeepOpen() Dim Result As Long ' استخدام /k بدلاً من /c لإبقاء نافذة CMD مفتوحة بعد تنفيذ الأمر On Error Resume Next Result = ExecuteWScript("cmd.exe /k dir", WindowNormal, False) Err.Clear ' مسح أي أخطاء سابقة If Err.Number = 0 Then MsgBox "النتيجة: " & Result Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub ' مثال لاستدعاء ExecuteWithTimeout لتشغيل CMD Sub TestExecuteWithTimeoutCMD() Dim ProcessId As Long ' تشغيل CMD مع أمر dir وانتظار 5 ثوانٍ كحد أقصى On Error Resume Next ProcessId = ExecuteWithTimeout("cmd.exe /k dir", WindowNormal, 5000) Err.Clear ' مسح أي أخطاء سابقة If Err.Number = PROCESS_TERMINATED Then MsgBox "اكتملت العملية برمز الخروج: " & ProcessId ElseIf Err.Number = 0 Then MsgBox "معرف العملية: " & ProcessId & " (انتهت المهلة)" Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub ' مثال لاستدعاء ExecuteWithTimeout مع RunAsAdmin وإعادة المحاولة Sub TestExecuteWithTimeoutAdmin() Dim ProcessId As Long ' تشغيل CMD كمسؤول وانتظار 5 ثوانٍ كحد أقصى مع محاولتين On Error Resume Next ProcessId = ExecuteWithTimeout("cmd.exe /k dir", WindowNormal, 5000, True, 2) Err.Clear ' مسح أي أخطاء سابقة If Err.Number = PROCESS_TERMINATED Then MsgBox "اكتملت العملية برمز الخروج: " & ProcessId ElseIf Err.Number = 0 Then MsgBox "معرف العملية: " & ProcessId & " (انتهت المهلة)" Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub ' مثال لاستدعاء ExecuteWScriptCapture Sub TestExecuteWScriptCapture() Dim CommandOutput As String ' تنفيذ أمر dir والتقاط الناتج On Error Resume Next CommandOutput = ExecuteWScriptCapture("cmd.exe /c dir") Err.Clear ' مسح أي أخطاء سابقة If Err.Number = 0 Then MsgBox "ناتج الأمر:" & vbCrLf & CommandOutput Else MsgBox "حدث خطأ: " & Err.Description End If On Error GoTo 0 End Sub تمنياتى القلبيــــه بأكبر قدر ممكن من تحصيل المتعة والاستفاده
-
- 2
-
-
- shellwait
- shell
-
(و23 أكثر)
موسوم بكلمه :
- shellwait
- shell
- executor
- executewscript
- executewscriptcapture
- شخابيط
- شخابيط وأفكار
- شخابيط وافكار
- شخابيط ابو جودى
- ابو جوى
- ابوجودى
- ابو جودي
- ابوجودي
- أوفيسنا
- اوفيسنا
- منتديات اوفيسنا
- منتديات أوفيسنا
- قسم الاكسس
- الاكسس
- مايكروسوفت اكسس
- microsoft access
- ms access
- تنفيذ الأوامر والملفات في بيئة windows
- تنفيذ الأوامر
- تحكم دقيق في العمليات
-
السلام عليكم ورحمة الله وبركاته اليوم اقدم لك وظيفة : ( مُطَهَّرُ النُّصُوصِ الْعَرَبِيَّةِ - الإصدار الثانى ) باختصار بعد هذا الموضوع : اداة مطهر النصوص المرنه - FlexiTextSanitizer الوصف: هي أداة تهدف إلى تنظيف النصوص العربية (وغيرها) بكفاءة عالية مع دعم واسع للتخصيص. توفر الدالة الرئيسية خيارات متعددة لمعالجة النصوص بما في ذلك تطبيع الأحرف العربية إزالة الحركات التحكم في الأرقام والأحرف الخاصة إضافة أقواس تلقائية حول الأرقام الاحتفاظ بالرموز الرياضية مثل √ و∑ المميزات الرئيسية: دعم اللغات: عربية لاتينية أو كلاهما التحكم في الأرقام والرموز: الاحتفاظ بها إزالتها أو إضافة أقواس تلقائية معالجة علامات الترقيم: الاحتفاظ بها كلها إزالتها أو الاكتفاء بالفواصل والنقاط دعم الرموز الرياضية: الاحتفاظ برموز مثل ∞ و≠ في الحالات المحددة التطبيع: توحيد الأحرف العربية (مثل تحويل إِ إلى ا). كيف تعمل؟ المدخلات: نص خام مع خيارات اختيارية (تطبيع - لغة - معالجة - ترقيم) المعالجة: تطبيع الأحرف (اختياري) إزالة الحركات إضافة أقواس حول الأرقام (إذا طُلب) تنظيف النص بناءً على نمط محدد تقليص المسافات المخرجات: نص نظيف و منسق حسب الخيارات المحددة الكود داخل الوحدة النمطية العامة ' تعداد لتحديد وضع اللغة Public Enum LanguageMode ArabicOnly = 0 ' اللغة العربية فقط ArabicAndLatin = 1 ' اللغة العربية واللاتينية LatinOnly = 2 ' اللغة اللاتينية فقط End Enum ' تعداد لتحديد وضع المعالجة Public Enum ProcessingMode KeepAll = 0 ' الاحتفاظ بالأرقام والأحرف الخاصة removeNumbers = 1 ' إزالة الأرقام فقط KeepNumbersOnly = 2 ' الاحتفاظ بالأرقام وإزالة الأحرف الخاصة CleanAll = 3 ' تنظيف كامل (إزالة الأرقام والأحرف الخاصة) KeepBrackets = 4 ' الاحتفاظ بالأرقام والأقواس (مع إضافتها تلقائيًا) KeepSpecialSymbols = 5 ' الاحتفاظ بالرموز الرياضية والخاصة End Enum ' تعداد لتحديد معالجة علامات الترقيم Public Enum punctuationMode KeepAllPunctuation = 0 ' الاحتفاظ بجميع علامات الترقيم RemoveAllPunctuation = 1 ' إزالة جميع علامات الترقيم KeepBasicPunctuation = 2 ' الاحتفاظ فقط بالفواصل والنقاط (, .) End Enum ' الدالة الرئيسية: FlexiTextSanitizer Public Function FlexiTextSanitizer(inputText As String, Optional normalize As Boolean = False, _ Optional langMode As LanguageMode = ArabicOnly, _ Optional processMode As ProcessingMode = KeepAll, _ Optional punctuationMode As punctuationMode = KeepAllPunctuation, _ Optional customSpecialChars As String = "()،؛") As String On Error GoTo ErrorHandler If Nz(inputText, "") = "" Then FlexiTextSanitizer = "" Exit Function End If Dim sanitizedText As String sanitizedText = Trim(inputText) ' الخطوة 1: التطبيع إذا طُلب If normalize Then Dim charReplacementPairs As Variant charReplacementPairs = Array( _ Array(ChrW(1573), ChrW(1575)), _ Array(ChrW(1571), ChrW(1575)), _ Array(ChrW(1570), ChrW(1575)), _ Array(ChrW(1572), ChrW(1608)), _ Array(ChrW(1574), ChrW(1609)), _ Array(ChrW(1609), ChrW(1610)), _ Array(ChrW(1577), ChrW(1607)), _ Array(ChrW(1705), ChrW(1603)), _ Array(ChrW(1670), ChrW(1580))) Dim pair As Variant For Each pair In charReplacementPairs sanitizedText = Replace(sanitizedText, pair(0), pair(1)) Next End If ' الخطوة 2: إزالة الحركات باستخدام RegExp Dim regEx As Object Set regEx = CreateObject("VBScript.RegExp") regEx.Global = True regEx.Pattern = "[\u064B-\u0652\u0670]" ' نطاق الحركات العربية sanitizedText = regEx.Replace(sanitizedText, "") ' إزالة علامة السؤال بشكل افتراضي sanitizedText = Replace(sanitizedText, "?", "") ' الخطوة 3: إضافة أقواس تلقائية حول الأرقام إذا طُلب (KeepBrackets) If processMode = KeepBrackets Then regEx.Pattern = "(\b[\u0660-\u0669\u0030-\u0039]+\b)" ' الأرقام العربية واللاتينية sanitizedText = regEx.Replace(sanitizedText, "($1)") End If ' الخطوة 4: بناء نمط الأحرف المسموح بها Dim allowedPattern As String Select Case langMode Case ArabicOnly allowedPattern = "\u0621-\u064A" ' الأحرف العربية Case ArabicAndLatin allowedPattern = "\u0621-\u064A\u0041-\u007A" ' العربية واللاتينية (A-Z, a-z) Case LatinOnly allowedPattern = "\u0041-\u007A" ' اللاتينية فقط End Select ' إضافة الأرقام والأحرف الخاصة بناءً على وضع المعالجة Select Case processMode Case KeepAll allowedPattern = allowedPattern & "\u0660-\u0669\u0030-\u0039" & EscapeRegExChars(customSpecialChars) Case removeNumbers allowedPattern = allowedPattern & EscapeRegExChars(customSpecialChars) Case KeepNumbersOnly allowedPattern = allowedPattern & "\u0660-\u0669\u0030-\u0039" Case CleanAll ' لا شيء يُضاف (تنظيف كامل) Case KeepBrackets allowedPattern = allowedPattern & "\u0660-\u0669\u0030-\u0039\(\)" ' الاحتفاظ بالأرقام والأقواس Case KeepSpecialSymbols allowedPattern = allowedPattern & "\u0660-\u0669\u0030-\u0039\u2200-\u22FF" ' الأرقام والرموز الرياضية End Select ' إضافة علامات الترقيم بناءً على وضع المعالجة Select Case punctuationMode Case KeepAllPunctuation allowedPattern = allowedPattern & "!""#$%&'()*+,-./:;<=>?@[\\]^_`{|}~،؛" Case RemoveAllPunctuation ' لا شيء يُضاف (إزالة كل علامات الترقيم) Case KeepBasicPunctuation allowedPattern = allowedPattern & ",." End Select ' إضافة المسافة دائمًا وتطبيق النمط regEx.Pattern = "[^" & allowedPattern & "\s]" ' إزالة كل ما هو خارج النطاق sanitizedText = regEx.Replace(sanitizedText, "") ' الخطوة 5: تقليص المسافات المتعددة إلى واحدة regEx.Pattern = "\s+" sanitizedText = regEx.Replace(sanitizedText, " ") sanitizedText = Trim(sanitizedText) ' الخطوة 6: إرجاع النتيجة If Len(Trim(Nz(sanitizedText, ""))) = 0 Then FlexiTextSanitizer = vbNullString Else FlexiTextSanitizer = sanitizedText End If Exit Function ErrorHandler: Debug.Print "خطأ في FlexiTextSanitizer: " & Err.Description FlexiTextSanitizer = "" End Function ' دالة مساعدة: EscapeRegExChars Private Function EscapeRegExChars(chars As String) As String Dim specialChars As Variant Dim i As Integer specialChars = Array("^", "$", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", "|", "\\", "`", "~", "&", "%", "#", "@", "<", ">") For i = LBound(specialChars) To UBound(specialChars) chars = Replace(chars, specialChars(i), "\" & specialChars(i)) Next i EscapeRegExChars = chars End Function اضافة توثيق وشرح للكود فى رأس الموديول ليكون مفهوما ولايضاح الية الاستدعاء بالسيناريوهات المختلفة والممكنة وهذا اختياريا يمكن وضعه قبل الكود السابق ' توثيق الموديول: ' الغرض: هذا الموديول يحتوي على دالة FlexiTextSanitizer لتنظيف النصوص بدقة وسرعة مع دعم مرن للغات (العربية واللاتينية)، الأحرف الخاصة، علامات الترقيم، والرموز الرياضية. ' يستخدم تعدادات (Enums) لتسهيل الاستدعاء وتقليل الأخطاء، ويتيح التحكم الكامل في معالجة النصوص. ' ' سيناريوهات الاستدعاء: ' 1. تنظيف النص مع الاحتفاظ بالأرقام والأحرف الخاصة وعلامات الترقيم بدون تطبيع: ' FlexiTextSanitizer(inputText, False, ArabicOnly, KeepAll, KeepAllPunctuation) ' - مثال الناتج: "إشراف على بعض الأماكن أو المكان رقم (5 - 5)" ' 2. تنظيف النص مع إزالة الأرقام بدون تطبيع: ' FlexiTextSanitizer(inputText, False, ArabicOnly, RemoveNumbers, KeepAllPunctuation) ' - مثال الناتج: "إشراف على بعض الأماكن أو المكان رقم" ' 3. تنظيف النص مع الاحتفاظ بالأرقام فقط مع تطبيع: ' FlexiTextSanitizer(inputText, True, ArabicOnly, KeepNumbersOnly, KeepAllPunctuation) ' - مثال الناتج: "اشراف علي بعض الاماكن او المكان رقم 5 - 5" ' 4. تنظيف كامل مع تطبيع وإزالة علامات الترقيم: ' FlexiTextSanitizer(inputText, True, ArabicOnly, CleanAll, RemoveAllPunctuation) ' - مثال الناتج: "اشراف علي بعض الاماكن او المكان رقم" ' 5. تنظيف النص مع الاحتفاظ بالأرقام والأقواس (تلقائية) والفواصل والنقاط مع تطبيع: ' FlexiTextSanitizer(inputText, True, ArabicOnly, KeepBrackets, KeepBasicPunctuation) ' - مثال الناتج: "اشراف علي, بعض الاماكن او المكان رقم (5).(5)" ' 6. تنظيف النص مع دعم العربية واللاتينية والأحرف الخاصة وعلامات الترقيم: ' FlexiTextSanitizer(inputText, False, ArabicAndLatin, KeepAll, KeepAllPunctuation, "().,") ' - مثال الناتج: "إشراف على بعض الأماكن أو المكان رقم (5 - 5) Supervision" ' 7. تنظيف النص مع إزالة جميع علامات الترقيم: ' FlexiTextSanitizer(inputText, False, ArabicOnly, KeepAll, RemoveAllPunctuation) ' - مثال الناتج: "إشراف على بعض الأماكن أو المكان رقم 5 5" ' 8. تنظيف النص مع الاحتفاظ بالفواصل والنقاط فقط: ' FlexiTextSanitizer(inputText, False, ArabicOnly, KeepAll, KeepBasicPunctuation) ' - مثال الناتج: "إشراف على, بعض الأماكن أو المكان رقم 5.5" ' 9. تنظيف نص يحتوي على علامات ترقيم كثيرة: ' FlexiTextSanitizer("!!!؟؟؟...،،،:::;;;---___***((()))", False, ArabicOnly, KeepAll, KeepAllPunctuation) ' - مثال الناتج: "!!!...،،،:::;;;---___***(())" ' 10. تنظيف نص يحتوي على رموز رياضية مع الاحتفاظ بها: ' FlexiTextSanitizer("√∑∫∏∂∆∞ ≠ ± × ÷", False, ArabicAndLatin, KeepSpecialSymbols, RemoveAllPunctuation) ' - مثال الناتج: "√∑∫∏∂∆∞ ≠ ± × ÷" ' 11. تطبيع جميع الأشكال الممكنة: ' FlexiTextSanitizer("إِ، أ، إ، ؤ، ئ، ى، ة، ك، چ", True, ArabicOnly, KeepAll, KeepAllPunctuation) ' - مثال الناتج: "ا، ا، ا، و، ي، ي، ه، ك، ج" ولكن ملحوطة صغيرة طبعا وللاسف محرر الاكواد هنا مع الاكسس فقيير جدا بعكس لغات البرمجة الاخرى لا يقبل الرموز لذلك الرموز الرياضية مثل : √∑∫∏∂∆∞ سوف تتغير داخل المحرر الى علامات استفهام والان داله يمكن اضافتها فى نهاية الكود وهى مجرد للتجربة طباعه نتائج التجربه فى النافذة الفوريه ليكون المبرمج مطلعا وملما بالنتائج ' اختبار الدالة مع السيناريوهات المطلوبة Sub TestFlexiTextSanitizer() Dim inputText As String inputText = "إِشْرَافٍ عَلَى? بَعْضِ الْأَمَاكِنِ أَوْ الْمَكَانِ رَقْمٌ Supervision of some places or place number 5 - 5" Debug.Print "النص الأصلي: " & inputText Debug.Print "------------------------------------" Debug.Print "السيناريو 1 (تنظيف، الاحتفاظ بالأرقام والأحرف الخاصة، بدون تطبيع):" Debug.Print FlexiTextSanitizer(inputText, False, ArabicOnly, KeepAll, KeepAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 2 (تنظيف، إزالة الأرقام، بدون تطبيع):" Debug.Print FlexiTextSanitizer(inputText, False, ArabicOnly, removeNumbers, KeepAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 3 (تنظيف، الاحتفاظ بالأرقام، مع تطبيع):" Debug.Print FlexiTextSanitizer(inputText, True, ArabicOnly, KeepNumbersOnly, KeepAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 4 (تنظيف كامل، مع تطبيع):" Debug.Print FlexiTextSanitizer(inputText, True, ArabicOnly, CleanAll, RemoveAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 5 (تنظيف، الاحتفاظ بالأرقام والأقواس، مع تطبيع):" Debug.Print FlexiTextSanitizer(inputText, True, ArabicOnly, KeepBrackets, KeepBasicPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 6 (العربية واللاتينية مع أحرف خاصة مخصصة والاحتفاظ بجميع علامات الترقيم):" Debug.Print FlexiTextSanitizer(inputText, False, ArabicAndLatin, KeepAll, KeepAllPunctuation, "().,") Debug.Print "------------------------------------" Debug.Print "السيناريو 7 (العربية فقط، إزالة جميع علامات الترقيم):" Debug.Print FlexiTextSanitizer(inputText, False, ArabicOnly, KeepAll, RemoveAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 8 (العربية فقط، الاحتفاظ بالفواصل والنقاط فقط):" Debug.Print FlexiTextSanitizer(inputText, False, ArabicOnly, KeepAll, KeepBasicPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 9 (نص يحتوي على علامات ترقيم كثيرة جدًا):" Debug.Print FlexiTextSanitizer("!!!؟؟؟...،،،:::;;;---___***((()))", False, ArabicOnly, KeepAll, KeepAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 10 (نص يحتوي على رموز رياضية ورموز خاصة):" Debug.Print FlexiTextSanitizer(ChrW(8730) & ChrW(8721) & ChrW(8747) & ChrW(8719) & ChrW(8706) & ChrW(8710) & ChrW(8734) & ChrW(32) & ChrW(8800) & ChrW(32) & ChrW(177) & ChrW(32) & ChrW(215) & ChrW(32) & ChrW(247), False, ArabicAndLatin, KeepSpecialSymbols, RemoveAllPunctuation) Debug.Print "------------------------------------" Debug.Print "السيناريو 11 (تطبيع جميع الأشكال الممكنة):" Debug.Print FlexiTextSanitizer("إِ، أ، إ، ؤ، ئ، ى، ة، ك، چ", True, ArabicOnly, KeepAll, KeepAllPunctuation) Debug.Print "------------------------------------" End Sub
-
- 2
-
-
- مُطَهَّرُ النُّصُوصِ الْعَرَبِيَّةِ - الإصدار الثانى
- مطهر النصوص العربية
-
(و38 أكثر)
موسوم بكلمه :
- مُطَهَّرُ النُّصُوصِ الْعَرَبِيَّةِ - الإصدار الثانى
- مطهر النصوص العربية
- ازالة المسافات الزائدة
- ازالة التشكيل
- ازالة الحركات
- تنظيف النص
- الابقاء على النص فقط
- حل مشكلة الهمزات
- الهمزات
- الهمزة والبحث
- الياء
- الياء والياء المنقوطة
- مشكلة الهاء والتاء المربوطة
- مشكله النصوص
- توحيد الحروف
- توحيد الحرف
- تطهير النص
- التشكيل
- التشكيل تنظيف التشكيل
- تنظيف
- تطهير
- حلول مشاكل الحركات والتشكيل
- شخابيط
- شخابيط وأفكار
- شخابيط وافكار
- شخابيط ابو جودى
- ابو جوى
- ابوجودى
- ابو جودى
- ابو جودي
- اوفيسنا
- منتديات اوفيسنا
- قسم الاكسس
- الاكسس
- مايكروسوفت اكسس
- الهمزة و البحث
- microsoft access
- ms access
- أوفيسنا
- من
-
السلام عليكم ورحمة الله وبركاته اقدم اليكم مكتبة مرنة وشاملة و متقدمة لإدارة و التعامل مع الملفات والمجلدات قمت بكتابتها بشكل مرن وإحترافي بمعنى الكلمة يحدد ما إذا كان المستخدم سيختار ملفًا أو مجلدًا يحدد شكل الإخراج (المسار الكامل، الاسم فقط، أو الاسم مع الامتداد) تصنيف الملفات حسب نوعها و تصفية الملفات المعروضة اختيار متعدد أو فردي اليكم الأكواد كاملة هديــــة لأخوانى وأحبابى Option Compare Database Option Explicit ' Global variables for file selection and allowed extensions Public IsFolderMode As Boolean ' Toggle folder selection mode Public AllowedExtensions As Collection ' Store allowed file extensions ' Enumeration for File Dialog Types Public Enum FileDialogType FilePicker = 1 ' Dialog for selecting files FolderPicker = 4 ' Dialog for selecting folders End Enum ' Enumeration for processing file path Public Enum FileProcessingMode FullPath = 1 ' Return the full file path NameWithoutExtension = 2 ' Return the file name without extension NameWithExtension = 3 ' Return the file name with extension End Enum ' Enumeration for file categories Public Enum FileCategory AccessFiles = 1 ' Access Database files (accdb, mdb, accda, etc.) ExcelFiles = 2 ' Excel files (xlsx, xls, xlsm, etc.) WordFiles = 3 ' Word files (docx, doc, docm, etc.) ImageFiles = 4 ' Images category (jpg, png, gif, bmp, tiff, etc.) AudioFiles = 5 ' Audio category (mp3, wav, ogg, flac, etc.) VideoFiles = 6 ' Video category (mp4, avi, mov, mkv, etc.) AcrobatFiles = 7 ' Acrobat PDF files (pdf) TextFiles = 8 ' Text files (txt, csv, log, md, etc.) PowerPointFiles = 9 ' PowerPoint files (pptx, ppt, pptm, etc.) CompressedFiles = 10 ' Compressed files (zip, rar, 7z, tar, gz, etc.) CodeFiles = 11 ' Code files (html, css, js, php, py, java, etc.) ExecutableFiles = 12 ' Executable files (exe, bat, cmd, apk, etc.) AllFiles = 13 ' All file types (*.*) End Enum ' Initialize the allowed extensions for a specific file category Sub InitializeExtensions(ByVal Category As FileCategory) Set AllowedExtensions = New Collection Select Case Category ' Access Database files Case AccessFiles AddExtensions Array("accda", "accdb", "accde", "accdr", "accdt", "accdw", "mda", "mdb", "mde", "mdf", "mdw") ' Excel files Case ExcelFiles AddExtensions Array("xlsx", "xls", "xlsm", "xlsb", "xltx", "xltm") ' Word files Case WordFiles AddExtensions Array("docx", "doc", "docm", "dotx", "dotm", "rtf", "odt") ' Image files Case ImageFiles AddExtensions Array("jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "ico", "webp", "heif", "heic") ' Audio files Case AudioFiles AddExtensions Array("mp3", "wav", "ogg", "flac", "aac", "m4a", "wma", "alac", "opus", "aiff") ' Video files Case VideoFiles AddExtensions Array("mp4", "avi", "mov", "mkv", "flv", "wmv", "webm", "mpeg", "mpg", "3gp", "ts") ' Acrobat PDF files Case AcrobatFiles AllowedExtensions.Add "pdf" ' Text files Case TextFiles AddExtensions Array("txt", "csv", "log", "md", "rtf") ' PowerPoint files Case PowerPointFiles AddExtensions Array("pptx", "ppt", "ppsx", "pps", "pptm", "potx", "potm") ' Compressed files (Archives) Case CompressedFiles AddExtensions Array("zip", "rar", "7z", "tar", "gz", "tar.gz", "tgz", "xz", "bz2") ' Code files Case CodeFiles AddExtensions Array("html", "css", "js", "php", "py", "java", "cpp", "c", "rb", "swift", "go", "ts") ' Executable files Case ExecutableFiles AddExtensions Array("exe", "bat", "cmd", "msi", "apk", "app", "dmg", "jar") ' All file types Case AllFiles AllowedExtensions.Add "*.*" Case Else MsgBox "Invalid category provided!", vbCritical End Select End Sub ' Add an array of extensions to the AllowedExtensions collection Private Sub AddExtensions(ByVal ExtensionsArray As Variant) Dim Extension As Variant For Each Extension In ExtensionsArray AllowedExtensions.Add Extension Next Extension End Sub ' Display a file or folder dialog and return the selected files Function GetFiles(Optional ByVal Extensions As Collection = Nothing, Optional ByVal SingleFile As Boolean = False) As Collection Dim FileDialog As Object Dim FolderDialog As Object Dim SelectedFiles As New Collection Dim FolderPath As String Dim FilterString As String On Error GoTo ErrorHandler ' Build the file dialog filter FilterString = BuildFilterString(Extensions) If Not IsFolderMode Then ' File selection dialog Set FileDialog = Application.FileDialog(FileDialogType.FilePicker) With FileDialog .Title = "Select File(s)" .AllowMultiSelect = Not SingleFile .Filters.Clear .Filters.Add "Allowed Files", FilterString If .Show = -1 Then AddSelectedFilesToCollection FileDialog, SingleFile, SelectedFiles End If End With Else ' Folder selection dialog Set FolderDialog = Application.FileDialog(FileDialogType.FolderPicker) With FolderDialog .Title = "Select Folder" If .Show = -1 Then FolderPath = .SelectedItems(1) SelectedFiles.Add FolderPath End If End With End If ' Return the selected files or folder If SelectedFiles.Count > 0 Then Set GetFiles = SelectedFiles Else MsgBox "No files or folder selected.", vbExclamation Set GetFiles = Nothing Exit Function End If CleanUp: Set FileDialog = Nothing Set FolderDialog = Nothing Exit Function ErrorHandler: MsgBox "An error occurred: " & Err.Description, vbCritical Resume CleanUp End Function ' Build the file dialog filter string Private Function BuildFilterString(ByVal Extensions As Collection) As String Dim Filter As String Dim Extension As Variant If Not Extensions Is Nothing Then For Each Extension In Extensions Filter = Filter & "*." & Extension & ";" Next Extension If Len(Filter) > 0 Then Filter = Left(Filter, Len(Filter) - 1) Else Filter = "*.*" End If BuildFilterString = Filter End Function ' Add selected files to the collection Private Sub AddSelectedFilesToCollection(ByVal Dialog As Object, ByVal SingleFile As Boolean, ByRef FilesCollection As Collection) Dim Index As Long If SingleFile Then FilesCollection.Add Dialog.SelectedItems(1) Else For Index = 1 To Dialog.SelectedItems.Count FilesCollection.Add Dialog.SelectedItems(Index) Next Index End If End Sub ' Function to check if the file extension is allowed Function IsAllowedExtension(ByVal strExt As String, ByVal colExtensions As Collection) As Boolean Dim varExt As Variant If colExtensions Is Nothing Or colExtensions.Count = 0 Then IsAllowedExtension = True ' Allow all extensions if colExtensions is Nothing or empty Exit Function End If For Each varExt In colExtensions If LCase(strExt) = LCase(varExt) Then IsAllowedExtension = True Exit Function End If Next varExt IsAllowedExtension = False End Function ' Subroutine to select a folder and retrieve all files based on allowed extensions Sub SelectFilesInFolder(ByVal FileCategoryType As FileCategory) Dim SelectedFiles As Collection ' Collection to hold the selected files Dim FolderPath As String ' Folder path selected by the user Dim CurrentFileName As String ' Current file name during folder iteration Dim FileExtension As String ' File extension for the current file Dim FilteredFiles As New Collection ' Collection to hold filtered files Dim FileItem As Variant ' Variable to iterate through filtered files On Error GoTo ErrorHandler ' Handle errors if they occur ' Enable folder selection mode IsFolderMode = True ' Initialize allowed extensions for the specified file category InitializeExtensions FileCategoryType ' Prompt user to select a folder Set SelectedFiles = GetFiles(Nothing, False) ' Pass Nothing for extensions as folder mode doesn't filter by type ' Check if a folder was selected If Not SelectedFiles Is Nothing And SelectedFiles.Count > 0 Then ' Get the first (and only) selected folder path FolderPath = SelectedFiles(1) ' Start iterating through all files in the selected folder CurrentFileName = Dir(FolderPath & "\*.*") ' Retrieve the first file in the folder Do While CurrentFileName <> "" ' Extract file extension and convert it to lowercase FileExtension = LCase(Split(CurrentFileName, ".")(UBound(Split(CurrentFileName, ".")))) ' Check if the file extension is allowed and add it to the filtered collection If IsAllowedExtension(FileExtension, AllowedExtensions) Then FilteredFiles.Add FolderPath & "\" & CurrentFileName End If ' Retrieve the next file in the folder CurrentFileName = Dir Loop ' If there are filtered files, display their paths If FilteredFiles.Count > 0 Then For Each FileItem In FilteredFiles Debug.Print "Selected File: " & FileItem Next FileItem Else MsgBox "No files found matching the allowed extensions.", vbExclamation End If Else MsgBox "No folder selected.", vbExclamation End If Exit Sub ' Error handler to catch and display error 91 (and other errors if any) ErrorHandler: If Err.Number = 91 Then Exit Sub Else MsgBox "An unexpected error occurred: " & Err.Description, vbCritical End If Resume Next End Sub Sub SelectFolderPath() On Error GoTo ErrorHandler ' Handle errors if they occur ' Collection to hold the selected files Dim colFiles As Collection IsFolderMode = True ' Set folder mode to true for folder selection Set colFiles = GetFiles(Nothing, False) ' Pass Nothing for colExtensions as we are dealing with folders On Error Resume Next If Not colFiles Is Nothing And colFiles.Count > 0 Then PrintFilePaths colFiles Else MsgBox "No folder selected.", vbExclamation End If Exit Sub ' Error handler to catch and display error 91 (and other errors if any) ErrorHandler: If Err.Number = 91 Then Exit Sub Else MsgBox "An unexpected error occurred: " & Err.Description, vbCritical End If Resume Next End Sub ' Subroutine to demonstrate single file selection with specific extensions Sub SelectSingleFile(ByVal FileCategoryType As FileCategory) On Error GoTo ErrorHandler ' Handle errors if they occur ' Collection to hold the selected files Dim SelectedFiles As Collection ' Set file selection mode IsFolderMode = False ' Initialize allowed extensions for the specified file category InitializeExtensions FileCategoryType ' Prompt user to select a single file with allowed extensions Set SelectedFiles = GetFiles(AllowedExtensions, True) ' Print selected file path(s) PrintFilePaths SelectedFiles Exit Sub ' Error handler to catch and display error 91 (and other errors if any) ErrorHandler: If Err.Number = 91 Then Exit Sub Else MsgBox "An unexpected error occurred: " & Err.Description, vbCritical End If Resume Next End Sub ' Subroutine to demonstrate multiple file selection with specific extensions Sub SelectMultipleFiles(ByVal FileCategoryType As FileCategory) On Error GoTo ErrorHandler ' Handle errors if they occur ' Collection to hold the selected files Dim SelectedFiles As Collection ' Set file selection mode IsFolderMode = False ' Initialize allowed extensions for the specified file category InitializeExtensions FileCategoryType ' Prompt user to select multiple files with allowed extensions Set SelectedFiles = GetFiles(AllowedExtensions, False) ' Print selected file path(s) PrintFilePaths SelectedFiles Exit Sub ' Error handler to catch and display error 91 (and other errors if any) ErrorHandler: If Err.Number = 91 Then Exit Sub Else MsgBox "An unexpected error occurred: " & Err.Description, vbCritical End If Resume Next End Sub ' Subroutine to print file paths from a collection Sub PrintFilePaths(ByVal Files As Collection) ' Variable to iterate through filtered files Dim FileItem As Variant ' Check if the collection is valid and contains files If Not Files Is Nothing And Files.Count > 0 Then For Each FileItem In Files Debug.Print "Selected File: " & FileItem Next FileItem Else MsgBox "No files were selected or matched the allowed extensions.", vbExclamation End If End Sub ' Subroutine to process file paths, extract name, name without extension, and extension Sub ProcessFilePaths(ByVal colFiles As Collection) ' Variable to iterate through the collection Dim varFilePath As Variant ' Variable to hold the current file path as a string Dim strFilePath As String ' Variables to hold extracted components of the file path Dim fileName As String Dim fileNameWithoutExt As String Dim fileExt As String ' Check if the collection is not empty or Nothing If Not colFiles Is Nothing Then ' Loop through each file path in the collection For Each varFilePath In colFiles ' Assign the current file path to a string variable strFilePath = varFilePath ' Extract the file name from the full path fileName = GetFileNameFromPath(strFilePath) ' Extract the file name without the extension fileNameWithoutExt = GetFileNameWithoutExtension(strFilePath) ' Extract the file extension (including the dot) fileExt = GetFileExtension(strFilePath) ' ' Print the extracted information to the Immediate Window (Ctrl+G in VBA Editor) ' Debug.Print "Full Path: " & varFilePath ' Debug.Print "File Name: " & fileName ' Debug.Print "File Name Without Extension: " & fileNameWithoutExt ' Debug.Print "File Extension: " & fileExt ' Debug.Print "------------------------------" Next varFilePath Else ' Show a message box if the collection is empty or Nothing MsgBox "No files found.", vbInformation End If End Sub ' Function to extract the file name (including extension) from a full file path Function GetFileNameFromPath(FilePath As String) As String ' Check if the file path is empty If Len(FilePath) = 0 Then GetFileNameFromPath = "" ' Return an empty string if no path is provided Exit Function End If ' Search for the last backslash in the file path Dim pos As Long pos = InStrRev(FilePath, "\") ' Find the position of the last backslash ' If no backslash is found, check for forward slash (e.g., for web paths) If pos = 0 Then pos = InStrRev(FilePath, "/") ' Find the position of the last forward slash End If ' Extract and return the file name If pos > 0 Then GetFileNameFromPath = Mid(FilePath, pos + 1) ' Return everything after the last separator Else GetFileNameFromPath = FilePath ' If no separator is found, return the full path End If End Function ' Function to extract the file name without its extension from a full file path Function GetFileNameWithoutExtension(FilePath As String) As String ' Check if the file path is empty If Len(FilePath) = 0 Then GetFileNameWithoutExtension = "" ' Return an empty string if no path is provided Exit Function End If ' Search for the last backslash in the file path Dim posBackslash As Integer posBackslash = InStrRev(FilePath, "\") ' Find the position of the last backslash ' If no backslash is found, check for forward slash (e.g., for web paths) If posBackslash = 0 Then posBackslash = InStrRev(FilePath, "/") ' Find the position of the last forward slash End If ' Extract the file name (with extension) Dim fileName As String If posBackslash > 0 Then fileName = Mid(FilePath, posBackslash + 1) ' Extract the file name Else fileName = FilePath ' If no separator, the full path is considered the file name End If ' Search for the last dot in the file name to identify the extension Dim posDot As Integer posDot = InStrRev(fileName, ".") ' Find the position of the last dot ' Remove the extension if a dot is found If posDot > 0 Then GetFileNameWithoutExtension = Left(fileName, posDot - 1) ' Return the name without the extension Else GetFileNameWithoutExtension = fileName ' If no dot, return the full file name End If End Function ' Function to extract the file extension (including the dot) from a full file path Function GetFileExtension(FilePath As String) As String ' Check if the file path is empty If Len(FilePath) = 0 Then GetFileExtension = "" ' Return an empty string if no path is provided Exit Function End If ' Search for the last dot in the file path Dim posDot As Integer posDot = InStrRev(FilePath, ".") ' Find the position of the last dot ' Extract and return the file extension If posDot > 0 Then GetFileExtension = Mid(FilePath, posDot) ' Return everything after (and including) the last dot Else GetFileExtension = "" ' If no dot is found, return an empty string End If End Function ' Subroutine to save file paths or details into a database table ' Parameters: ' - SelectedFiles: Collection of selected file paths. ' - TableName: Name of the database table where data will be saved. ' - FieldName: Name of the field in the table to store the file information. ' - ProcessingMode: Determines how the file paths will be processed before saving. Default is FullPath. Sub SaveFileDetailsToTable(SelectedFiles As Collection, TableName As String, FieldName As String, Optional ByVal ProcessingMode As FileProcessingMode = FullPath) On Error GoTo ErrorHandler ' Handle errors if they occur Dim varFilePath As Variant Dim ProcessedValue As String ' Check if the SelectedFiles collection is valid and contains files If Not SelectedFiles Is Nothing And SelectedFiles.Count > 0 Then ' Loop through each file in the collection For Each varFilePath In SelectedFiles ' Determine how the file path should be processed based on ProcessingMode Select Case ProcessingMode Case FullPath ' Use the full file path as the value to save ProcessedValue = CStr(varFilePath) Case NameWithoutExtension ' Extract and use the file name without its extension ProcessedValue = GetFileNameWithoutExtension(CStr(varFilePath)) Case NameWithExtension ' Extract and use the file name including its extension ProcessedValue = GetFileNameFromPath(CStr(varFilePath)) Case Else ' Default to using the full file path ProcessedValue = CStr(varFilePath) End Select ' Construct the SQL statement to insert the processed value into the specified table and field Dim SQL As String SQL = "INSERT INTO [" & TableName & "] ([" & FieldName & "]) VALUES ('" & Replace(ProcessedValue, "'", "''") & "')" ' Execute the SQL statement to save the data into the database CurrentDb.Execute SQL, dbFailOnError Next varFilePath Else ' Display a message if no files were found in the collection MsgBox "No files found.", vbInformation End If Exit Sub ' Error handler to catch and display error 91 (and other errors if any) ErrorHandler: If Err.Number = 91 Then Exit Sub Else MsgBox "An unexpected error occurred: " & Err.Description, vbCritical End If Resume Next End Sub ' Test method to demonstrate saving file details to a table ' This subroutine selects files and saves their names without extensions into a database table Sub TestSaveResults() Dim SelectedFiles As Collection ' Set mode to file selection mode IsFolderMode = False ' Initialize allowed extensions for the specific category (e.g., images in this case) InitializeExtensions ImageFiles ' Prompt the user to select files based on the allowed extensions Set SelectedFiles = GetFiles(AllowedExtensions, False) ' Save the selected file names (without extensions) into the table "tblMedia" in the "fieldName" column SaveFileDetailsToTable SelectedFiles, "tblMedia", "fieldName", NameWithoutExtension End Sub ' Test the functionality of retrieving a folder path Sub TestGetFolderPath() ' Call the Select Folder function to get the folder path SelectFolderPath End Sub ' Test the functionality of selecting files in a folder based on the specified file category Sub TestSelectFilesInFolder() ' Call the SelectFilesInFolder function to select audio files from a folder SelectFilesInFolder AudioFiles End Sub ' Test the functionality of selecting a single file based on the specified file category Sub TestSelectSingleFile() ' Call the SelectSingleFile function to select a single audio file SelectSingleFile AudioFiles End Sub ' Test the functionality of selecting multiple files based on the specified file category Sub TestSelectMultipleFiles() ' Call the SelectMultipleFiles function to select multiple audio files SelectMultipleFiles AudioFiles End Sub
- 5 replies
-
- 6
-
-
-
- filedialog
- إستعراض
- (و17 أكثر)
-
السلام عليكم ورحمة الله تعالى وبركاته المصدر و الموضوع الاساسى : فى هذه المشاركة لأستاذى القدير و معلمى الجليل و والدى الحبيب الاستاذ جعفر ( @jjafferr ) بعد اذن استاذى الجليل و معلمى القدير وحتي تعم الفائدة أقتبس من الموضوع الأساسى بعض المقتطفات و التى هى الأساس : هناك 3 انواع من هذه القوائم : الثابته ، والمؤقته ، والمؤقته التي تحتاج الى كود. الثابته: وهي التي عندما نعملها ، تصبح مستقله عن الكود ، وتُحفظ وتبقى في قاعدة البيانات بعد إغلاقها ، ويمكننا ان نستوردها في قاعدة بيانات اخرى عندما نستورد احد/جميع كائنات قاعدة البيانات الآخرى ، بإستخدام : . ونختارها في النموذج : . او التقرير : هذا مثال لعمل الكود الاساس لعمل قائمة قطع/نسخ/لصق : ومن هنا يبدأ موضوعى المتواضع بإعادة هيكلة وبناء وتطوير وإضافة الاكواد حسب فهمى المتواضع وأفكارى البسيطة والضئيلة الشرح :اولا الاكواد فى الموديول :basCommandBarsConfiguration Option Compare Database Option Explicit ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Constants for button states and control types Public Const BUTTON_STATE_DOWN As Integer = -1 ' BUTTON_STATE_DOWN: Indicates that a button is in a pressed or activated state. ' This value is used to reflect the button's pressed status. Public Const BUTTON_STATE_UP As Integer = 0 ' BUTTON_STATE_UP: Indicates that a button is in its default, unpressed state. ' This value is used to reflect the button's normal, unpressed status. Public Const CONTROL_TYPE_BUTTON As Integer = 1 ' CONTROL_TYPE_BUTTON: Represents a button control type in a command bar or menu. ' Used to add buttons to a command bar or menu with various functionalities. Public Const CONTROL_TYPE_EDIT As Integer = 2 ' CONTROL_TYPE_EDIT: Represents an editable control type, such as a text box. ' Used to add an editable text field to a command bar or menu. Public Const CONTROL_TYPE_COMBOBOX As Integer = 4 ' CONTROL_TYPE_COMBOBOX: Represents a combo box control type in a command bar or menu. ' A combo box allows users to select from a list of predefined options or enter a custom value. Public Const CONTROL_TYPE_POPUP As Integer = 5 ' CONTROL_TYPE_POPUP: Represents a popup menu or sub-menu control type. ' Used to create a dropdown menu or context menu in a command bar. Public Const BAR_TYPE_POPUP As Integer = 5 ' BAR_TYPE_POPUP: Represents a popup menu bar type. ' Used to create a command bar that behaves as a popup menu (e.g., appears on right-click or when invoked). ' Variables for CommandBar and Controls Public commandBar As Object ' Represents the custom command bar (popup menu) object Public commandButton As Object ' Represents each button/control added to the command bar Public commandBarName As String ' Name of the custom command bar Public CtrlFilterPopup As Object ' Represents the popup control for text filters '================================================================================ ' Procedure : AddButtonToCommandBar ' Purpose : Adds a button to a command bar with specified properties. ' Parameters: ' - btn: The button object to be added to the command bar. ' - type: The type of control (button). ' - id: The ID of the button. ' - caption: The caption text for the button. ' - beginGroup (optional): Boolean to indicate if a separator should be added before the button. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to add a button to the command bar Private Sub AddButtonToCommandBar(ByRef controls As Object, _ ByVal controlType As Integer, _ ByVal faceId As Integer, _ ByVal caption As String, _ Optional ByVal beginGroup As Boolean = False) On Error Resume Next Set commandButton = controls.Add(controlType, faceId, , , False) If Not commandButton Is Nothing Then With commandButton .caption = caption .faceId = faceId .beginGroup = beginGroup End With End If On Error GoTo 0 End Sub '================================================================================ ' Procedure : AddFilterControls ' Purpose : Adds filter controls to the provided controls collection in a filter popup. ' Parameters: ' - controls: The controls collection to which the filter controls will be added. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to add filter controls to the filter popup Private Sub AddFilterControls(ByRef controls As Object) With controls .Add CONTROL_TYPE_BUTTON, 10077, , , False .Add CONTROL_TYPE_BUTTON, 10078, , , False .Add CONTROL_TYPE_BUTTON, 10079, , , False .Add CONTROL_TYPE_BUTTON, 12696, , , False .Add CONTROL_TYPE_BUTTON, 10080, , , False .Add CONTROL_TYPE_BUTTON, 10081, , , False .Add CONTROL_TYPE_BUTTON, 10082, , , False .Add CONTROL_TYPE_BUTTON, 10083, , , False .Add CONTROL_TYPE_BUTTON, 12697, , , False .Add CONTROL_TYPE_BUTTON, 10058, , , False .Add CONTROL_TYPE_BUTTON, 10069, , , False .Add CONTROL_TYPE_BUTTON, 10070, , , False End With End Sub '================================================================================ ' Procedure : ClipboardActionsSortFilterCommandBar ' Purpose : Creates and configures a custom command bar with ClipboardActions (cut, copy, paste), sort, and filter options. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to create and configure the copy, sort, and filter command bar Public Sub ClipboardActionsSortFilterCommandBar() On Error GoTo ErrorHandler ' Handle errors ' Define the name of the custom command bar commandBarName = "ClipboardActionsSortFilterCommandBar" ' Ensure this matches the name you are checking ' Delete the existing command bar with the same name, if any On Error Resume Next Set commandBar = CommandBars(commandBarName) If Not commandBar Is Nothing Then commandBar.Delete End If If Err.Number <> 0 Then Err.Clear ' Create a new command bar Set commandBar = CommandBars.Add(Name:=commandBarName, Position:=BAR_TYPE_POPUP, Temporary:=False) With commandBar ' Add buttons to the command bar Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 21, "Cut") Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 19, "Copy") Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 22, "Paste") Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 210, "Sort Ascending", True) Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 211, "Sort Descending") Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 640, "Filter By Selection", True) Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 3017, "Filter Excluding Selection") Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 605, "Remove Filter/Sort") ' Add Filter For button with a popup menu Set CtrlFilterPopup = .controls.Add(Type:=CONTROL_TYPE_POPUP, Temporary:=False) If Not CtrlFilterPopup Is Nothing Then CtrlFilterPopup.caption = "Text Filters" ' Ensure CtrlFilterPopup is a CommandBarPopup If TypeName(CtrlFilterPopup) = "CommandBarPopup" Then ' Remove any existing controls For Each commandButton In CtrlFilterPopup.controls commandButton.Delete Next commandButton ' Add new controls to CtrlFilterPopup Call AddFilterControls(CtrlFilterPopup.controls) End If End If ' Add Close Form/Report button Set commandButton = .controls.Add(Type:=CONTROL_TYPE_BUTTON, ID:=923, Temporary:=False) If Not commandButton Is Nothing Then commandButton.beginGroup = True commandButton.caption = ChrW(1573) & ChrW(1594) & ChrW(1604) & ChrW(1575) & ChrW(1602) ' Close commandButton.OnAction = "CloseCurrentItem" ' Action to call the CloseCurrentItem subroutine End If End With ' Clean up Set commandBar = Nothing Set commandButton = Nothing Set CtrlFilterPopup = Nothing Exit Sub ErrorHandler: ' MsgBox "An error occurred: " & Err.Description, vbExclamation ' Debug.Print "An error occurred in cmb_Copy_Sort_Filter : " & Err.Number & " | " & Err.Description Resume Next End Sub '================================================================================ ' Procedure : ClipboardActionsSortCommandBar ' Purpose : Creates and configures a custom command bar with ClipboardActions (cut, copy, paste), and sorting options. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to create and configure the custom command bar Public Sub ClipboardActionsSortCommandBar() On Error GoTo ErrorHandler ' Handle errors ' Define the name of the custom command bar commandBarName = "ClipboardActionsSortCommandBar" ' Name for the custom command bar ' Delete the existing command bar with the same name, if any On Error Resume Next Set commandBar = CommandBars(commandBarName) If Not commandBar Is Nothing Then commandBar.Delete End If If Err.Number <> 0 Then Err.Clear ' Add a new command bar (popup menu) with the specified name Set commandBar = CommandBars.Add(Name:=commandBarName, Position:=BAR_TYPE_POPUP, Temporary:=False) With commandBar ' Add buttons to the command bar using the new subroutine ' Add Cut button Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 21, ChrW(1602) & ChrW(1589)) ' Add Copy button Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 19, ChrW(1606) & ChrW(1587) & ChrW(1582)) ' Add Paste button Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 22, ChrW(1604) & ChrW(1589) & ChrW(1602)) ' Add Sort Ascending button Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 210, ChrW(1578) & ChrW(1585) & ChrW(1578) & ChrW(1610) & ChrW(1576) & ChrW(32) & ChrW(1578) & ChrW(1589) & ChrW(1575) & ChrW(1593) & ChrW(1583) & ChrW(1610), True) ' Add Sort Descending button Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 211, ChrW(1578) & ChrW(1585) & ChrW(1578) & ChrW(1610) & ChrW(1576) & ChrW(32) & ChrW(1578) & ChrW(1606) & ChrW(1575) & ChrW(1586) & ChrW(1604) & ChrW(1610), True) ' Add Close Form/Report button Set commandButton = .controls.Add(Type:=CONTROL_TYPE_BUTTON, ID:=923, Temporary:=False) If Not commandButton Is Nothing Then commandButton.beginGroup = True commandButton.caption = ChrW(1573) & ChrW(1594) & ChrW(1604) & ChrW(1575) & ChrW(1602) ' Close commandButton.OnAction = "CloseCurrentItem" ' Action to call the CloseCurrentItem subroutine End If End With ' Clean up Set commandBar = Nothing Set commandButton = Nothing Exit Sub ErrorHandler: ' MsgBox "An error occurred: " & Err.Description, vbExclamation ' Debug.Print "An error occurred in cmb_CustomMenu : " & Err.Number & " | " & Err.Description Resume Next End Sub '================================================================================ ' Procedure : ClipboardActionsCommandBar ' Purpose : Creates and configures a custom command bar with ClipboardActions (cut, copy, paste). '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to create and configure the copy command bar Public Sub ClipboardActionsCommandBar() On Error GoTo ErrorHandler ' Handle errors ' Define the name of the custom command bar commandBarName = "ClipboardActionsCommandBar" ' Delete the existing command bar with the same name, if any On Error Resume Next Set commandBar = CommandBars(commandBarName) If Not commandBar Is Nothing Then commandBar.Delete End If If Err.Number <> 0 Then Err.Clear ' Add a new command bar (popup menu) with the specified name Set commandBar = CommandBars.Add(Name:=commandBarName, Position:=BAR_TYPE_POPUP, Temporary:=False) With commandBar ' Add buttons to the command bar Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 21, ChrW(1602) & ChrW(1589)) ' Cut Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 19, ChrW(1606) & ChrW(1587) & ChrW(1582)) ' Copy Call AddButtonToCommandBar(.controls, CONTROL_TYPE_BUTTON, 22, ChrW(1604) & ChrW(1589) & ChrW(1602)) ' Paste End With ' Clean up Set commandBar = Nothing Exit Sub ErrorHandler: ' MsgBox "An error occurred: " & Err.Description, vbExclamation ' Debug.Print "An error occurred in SCM_Copy : " & Err.Number & " | " & Err.Description Resume Next End Sub '================================================================================ ' Procedure : ReportContextMenuCommandBar ' Purpose : Creates and configures a custom report command bar with various ' printing, setup, and export options for reports. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to create and configure the custom report command bar Public Sub ReportContextMenuCommandBar() On Error GoTo ErrorHandler ' Handle errors Dim exportSubMenu As Object ' New variable for sub-menu handling ' Define the command bar name commandBarName = "ReportContextMenuCommandBar" ' Delete the existing command bar with the same name, if any On Error Resume Next Set commandBar = CommandBars(commandBarName) If Not commandBar Is Nothing Then commandBar.Delete End If If Err.Number <> 0 Then Err.Clear ' Create the shortcut menu Set commandBar = CommandBars.Add(Name:=commandBarName, Position:=BAR_TYPE_POPUP, Temporary:=False) ' Ensure commandBar was created successfully If commandBar Is Nothing Then MsgBox "Failed to create command bar.", vbExclamation Exit Sub End If With commandBar.controls ' Add the Print command Call AddButtonToCommandBar(.Add(Type:=CONTROL_TYPE_BUTTON, ID:=2521), CONTROL_TYPE_BUTTON, 2521, "Quick Print") ' Add the Select Pages command Call AddButtonToCommandBar(.Add(Type:=CONTROL_TYPE_BUTTON, ID:=15948), CONTROL_TYPE_BUTTON, 15948, "Select Pages") ' Add the Page Setup command Call AddButtonToCommandBar(.Add(Type:=CONTROL_TYPE_BUTTON, ID:=247), CONTROL_TYPE_BUTTON, 247, "Page Setup") ' Add the Email Report as an Attachment command Call AddButtonToCommandBar(.Add(Type:=CONTROL_TYPE_BUTTON, ID:=2188), CONTROL_TYPE_BUTTON, 2188, "Email Report as an Attachment", True) ' Add the Save as PDF/XPS command Call AddButtonToCommandBar(.Add(Type:=CONTROL_TYPE_BUTTON, ID:=12499), CONTROL_TYPE_BUTTON, 12499, "Save as PDF/XPS") ' Add Export to Word and Excel commands as sub-items of the PDF/XPS button If .Count >= 5 Then ' Add sub-menu for PDF/XPS button Set exportSubMenu = .Item(5).controls.Add(Type:=CONTROL_TYPE_POPUP, Temporary:=False) exportSubMenu.caption = "Export Options" ' Add Export to Word Set commandButton = exportSubMenu.controls.Add(Type:=CONTROL_TYPE_BUTTON, ID:=11725, Temporary:=False) If Not commandButton Is Nothing Then commandButton.caption = "Export to Word..." commandButton.faceId = 42 End If ' Add Export to Excel Set commandButton = exportSubMenu.controls.Add(Type:=CONTROL_TYPE_BUTTON, ID:=11723, Temporary:=False) If Not commandButton Is Nothing Then commandButton.caption = "Export to Excel…" commandButton.faceId = 263 End If End If ' Add the Close Report command Call AddButtonToCommandBar(.Add(Type:=CONTROL_TYPE_BUTTON, ID:=923), CONTROL_TYPE_BUTTON, 923, "Close Report", True) End With ' Clean up Set commandBar = Nothing Set commandButton = Nothing Set exportSubMenu = Nothing Exit Sub ErrorHandler: ' MsgBox "An error occurred: " & Err.Description, vbExclamation ' Debug.Print "An error occurred in CreateReportShortcutMenu : " & Err.Number & " | " & Err.Description Resume Next End Sub '================================================================================ ' Procedure : CloseCurrentItem ' Purpose : Closes the currently active form or report in the application. If no form ' or report is active, it displays a message to the user. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to close the currently active form or report Public Sub CloseCurrentItem() On Error GoTo ErrorHandler Dim obj As Object Dim activeItemName As String Dim isFormActive As Boolean Dim isReportActive As Boolean ' Check if an active form is open and close it isFormActive = False For Each obj In Forms If obj.Name = Screen.ActiveForm.Name Then activeItemName = obj.Name isFormActive = True Exit For End If Next obj If isFormActive Then DoCmd.Close acForm, activeItemName Exit Sub End If ' Check if an active report is open and close it isReportActive = False For Each obj In Reports If obj.Name = Screen.ActiveReport.Name Then activeItemName = obj.Name isReportActive = True Exit For End If Next obj If isReportActive Then DoCmd.Close acReport, activeItemName Exit Sub End If ' If no form or report is active, display a message MsgBox "There is no active form or report to close.", vbExclamation Exit Sub ErrorHandler: ' MsgBox "An error occurred: " & Err.Description, vbExclamation ' Debug.Print "An error occurred: " & Err.Number & " | " & Err.Description Resume Next End Sub '================================================================================ ' Procedure : DeleteAllCommandBars ' Purpose : Deletes all custom (non-built-in) command bars. '================================================================================ ' Author: www.officena.net , Mohammed Essam, soul-angel@msn.com, July 2024. ' Subroutine to Deletes all custom command bars. Public Sub DeleteAllCommandBars() On Error GoTo ErrorHandler ' Handle errors Dim i As Integer Dim cmdBar As Object Dim cmdBarsCount As Integer ' Get the count of command bars cmdBarsCount = CommandBars.Count ' Iterate through all command bars in reverse order For i = cmdBarsCount To 1 Step -1 On Error Resume Next ' Ignore errors if they occur during deletion Set cmdBar = CommandBars(i) If Not cmdBar Is Nothing Then ' Check if the command bar is not built-in or default If Not cmdBar.BuiltIn Then cmdBar.Delete Debug.Print "CommandBar '" & cmdBar.Name & "' has been deleted." End If End If On Error GoTo ErrorHandler ' Restore error handling Next i ' Clean up Set cmdBar = Nothing Exit Sub ErrorHandler: ' Display a more specific error message ' MsgBox "An error occurred while trying to delete command bars: " & Err.Description, vbExclamation ' Debug.Print "An error occurred in DeleteAllCommandBars: " & Err.Number & " | " & Err.Description Resume Next End Sub الثوابت : BUTTON_STATE_DOWN: قيمة ثابتة تستخدم للإشارة إلى أن الزر في حالة ضغط أو تفعيل ويستخدم هذا لإظهار حالة الزر عند الضغط عليه BUTTON_STATE_UP: قيمة ثابتة تستخدم للإشارة إلى أن الزر في حالته الطبيعية أو غير المضغوط عليها يستخدم هذا لإظهار حالة الزر عند عدم الضغط عليه CONTROL_TYPE_BUTTON: قيمة ثابتة تستخدم لتمثيل نوع التحكم "زر" في شريط الأوامر : ( قائمة السياق ) CONTROL_TYPE_EDIT: قيمة ثابتة تستخدم لتمثيل نوع التحكم "محرر" مثل صندوق النص يستخدم لإضافة حقل نص قابل للتعديل في شريط الأوامر : ( قائمة السياق ) CONTROL_TYPE_COMBOBOX: قيمة ثابتة تستخدم لتمثيل نوع التحكم "قائمة منسدلة" القائمة المنسدلة تسمح للمستخدمين بالاختيار من قائمة محددة مسبقا أو إدخال قيمة مخصصة CONTROL_TYPE_POPUP: قيمة ثابتة تستخدم لتمثيل نوع التحكم "قائمة منبثقة" أو "قائمة فرعية" تُستخدم لإنشاء قائمة منسدلة أو قائمة سياقية في شريط الأوامر BAR_TYPE_POPUP: قيمة ثابتة تُستخدم لتمثيل نوع شريط الأوامر المنبثق. يُستخدم لإنشاء شريط أدوات يظهر عند النقر بالزر الأيمن أو عند استدعائه -------------- المتغيرات : commandBar: يمثل كائن شريط الأوامر المخصص (قائمة السياق) commandButton: يمثل كل زر/تحكم يتم إضافته إلى شريط الأوامر commandBarName: اسم شريط الأوامر المخصص CtrlFilterPopup: يمثل التحكم المنبثق للفلاتر النصية -------------- الدوال : دالة : AddButtonToCommandBar الغرض: إضافة زر إلى شريط الأوامر مع الخصائص المحددة المعلمات: controls: مجموعة التحكمات التي سيتم إضافة الزر إليها controlType: نوع التحكم (زر في هذه الحالة) faceId: معرف الأيقونة للزر caption: نص التسمية للزر beginGroup (اختياري): منطق لبدء مجموعة جديدة مع الزر، مما يضيف فاصلًا قبله -------------- دالة : AddFilterControls الغرض: إضافة عناصر التحكم بالفلاتر إلى مجموعة التحكمات المحددة في قائمة منبثقة للفلاتر المعلمات: controls: مجموعة التحكمات التي سيتم إضافة عناصر الفلاتر إليها -------------- دالة : ClipboardActionsSortFilterCommandBar الغرض: إنشاء وتكوين شريط أوامر مخصص يتضمن خيارات الحافظة (قص، نسخ، لصق)، والفرز، والفلاتر العملية: إنشاء شريط أوامر جديد ( قائمة السياق ) إضافة أزرار للقص، النسخ، اللصق، الفرز، والفلاتر إضافة قائمة منبثقة للفلاتر النصية إضافة زر لإغلاق النموذج/التقرير -------------- دالة : ClipboardActionsSortCommandBar الغرض: إنشاء وتكوين شريط أوامر جديد ( قائمة السياق ) يتضمن خيارات الحافظة (قص، نسخ، لصق), والفرز العملية: إنشاء شريط أوامر جديد إضافة أزرار للقص، النسخ، اللصق، والفرز إضافة زر لإغلاق النموذج/التقرير -------------- دالة : ClipboardActionsCommandBar الغرض: إنشاء وتكوين شريط أوامر مخصص يتضمن خيارات الحافظة (قص، نسخ، لصق) العملية: إنشاء شريط أوامر جديد إضافة أزرار للقص، النسخ، واللصق -------------- دالة : ReportContextMenuCommandBar الغرض: إنشاء وتكوين شريط أوامر مخصص لقائمة السياق الخاصة بالتقرير، يتضمن خيارات الطباعة، الإعداد، والتصدير العملية: إنشاء شريط أوامر جديد إضافة أزرار لطباعة، اختيار الصفحات، إعداد الصفحة، إرسال التقرير بالبريد الإلكتروني كمرفق، حفظ كـ PDF/XPS إضافة خيارات تصدير إلى Word و Excel كعناصر فرعية لزر PDF/XPS إضافة زر لإغلاق التقرير -------------- دالة : CloseCurrentItem الغرض: إغلاق النموذج أو التقرير النشط حاليا في التطبيق العملية: التحقق مما إذا كان هناك نموذج نشط وإغلاقه التقق مما إذا كان هناك تقرير نشط وإغلاقه -------------- دالة : DeleteAllCommandBars الغرض: حذف جميع أشرطة الأوامر المخصصة (غير المدمجة) في التطبيق العملية: الحصول على عدد أشرطة الأوامر: يتم الحصول على عدد أشرطة الأوامر الحالية باستخدام CommandBars.Count التكرار من آخر شريط أوامر إلى أول شريط أوامر (من النهاية إلى البداية) لضمان عدم حدوث أخطاء أثناء الحذف حذف أشرطة الأوامر: إذا لم يكن الشريط مدمجًا (أي أنه شريط مخصص) يتم حذف الشريط -------------- واخيرا استدعاء الدالة عند تحميل النموذج أو التقرير: استدعاء دالة: Call RoutineNameCustomCommandBar يتم استدعاء دالة مع تغيير RoutineNameCustomCommandBar باسم الدالة الخاصة بإنشاء وتكوين شريط الأوامر المخصص حيث تقوم بإنشاء أو تعديل شريط الأوامر (CommandBar) الخاص بالنموذج أو التقرير تعيين خاصية ShortcutMenuBar: Me.ShortcutMenuBar = RoutineNameCustomCommandBar يتم تعيين خاصية ShortcutMenuBar للنموذج أو التقرير إلى اسم شريط الأوامر الذي تم إنشاؤه أو تعديله أثناء استدعاء الدالة المخصصة بهذه الطريقة يتم ربط شريط الأوامر المخصص بقائمة الاختصارات (shortcut menu) للنموذج أو التقرير الحالي ارقام جميع الصور الموجودة في الاكسس والتى نستخدمها كمعلمة فى faceId معرف الأيقونة للزر المصادر: الموضوع الاساسى فى هذا المنتدى لأستاذى القدير و معلمى الجليل و والدى الحبيب الاستاذ جعفر https://www.officena.net/ib/topic/99557-القائمة-المختصرة-shortcut-menu/#comment-603366 http://dev-soln.com/access-shortcut-right-click-tool/ https://www.experts-exchange.com/articles/12904/Understanding-and-using-CommandBars-Part-II-Creating-your-own.html https://filedb.experts-exchange.com/incoming/2014/02_w06/833359/CommandBars-II.mdb https://www.experts-exchange.com/articles/18341/CommandBars-Part-III-Using-Built-in-Shortcut-Menus.html http://www.skrol29.com/us/vtools.php CommandBarsConfiguration.accdb
- 4 replies
-
- 3
-
-
- commandbarsconfiguration
- commandbars
-
(و21 أكثر)
موسوم بكلمه :
- commandbarsconfiguration
- commandbars
- commandbar
- قائمة السياق
- custom commandbar
- شريط الأوامر المخصص
- شريط الأوامر المخصص للنماذج والتقارير
- قائمة السياق المخصصة
- قائمة السياق المخصصة للنماذج والتقارير
- custom context menu for forms and reports
- أشرطة الأوامر المخصصة للنماذج والتقارير
- custom command bars for forms and reports
- ابو جوى
- شخابيط
- شخابيط وأفكار
- شخابيط ابو جودى
- شخابيط وافكار
- القائمة المختصرة
- القائمة المختصرة للنماذج والتقارير
- القائمة المختصرة للنماذج
- القائمة المختصرة للتقارير
- right click
- النقر اليمين
-
-تجهيز مجلدات وملف الصوت الخطوة الاولى قم بانشاء مجلد جديد فى مسار قاعدة البيانات الحالى باسم ( Resurce ) الخطوة الثانية قم بفتح المجلد السابق وقم بانشاء مجلد جديد بداخله باسم ( Audio Files ) الخطوة الثالثة قم بنسخ ملف صوت الى المجلد ( Audio Files ) اما بامتداد wav , .mp3. --------------------- -تجهيز قاعدة البيانات الخطوة الاولى قم بانشاء وحدة نمطية باسم ( modPlayAudio ) وقم بلصق الاكواد الاتية فى هذه الوحدة النمطية Option Compare Database Option Explicit #If VBA7 And Win64 Then Private Declare PtrSafe Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As Any, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long Private Declare PtrSafe Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal lBuffer As Long) As Long Private Declare PtrSafe Function playSound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long #Else Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As Any, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal lBuffer As Long) As Long Private Declare Function playSound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long #End If Const SND_ALIAS_SYSTEMASTERISK As String = "SystemAsterisk" Const SND_ALIAS_SYSTEMDEFAULT As String = "SystemDefault" Const SND_ALIAS_SYSTEMEXCLAMATION As String = "SystemExclamation" Const SND_ALIAS_SYSTEMEXIT As String = "SystemExit" Const SND_ALIAS_SYSTEMHAND As String = "SystemHand" Const SND_ALIAS_SYSTEMQUESTION As String = "SystemQuestion" Const SND_ALIAS_SYSTEMSTART As String = "SystemStart" Const SND_ALIAS_SYSTEMWELCOME As String = "SystemWelcome" Const SND_ALIAS_YouGotMail As String = "MailBeep" ' playsound Params Const SND_LOOP = &H8 Const SND_ALIAS = &H10000 Const SND_NODEFAULT = &H2 ' silence if no sound associated with event Const SND_ASYNC = &H1 ' play async (don't freeze program while sound is playing) Private sMusicFile As String Public soundOn As Boolean Dim mp3Path As String Dim wavPath As String Dim Play As Variant Public Sub Sound_MP3(ByVal File$) sMusicFile = GetShortPath(File) Play = mciSendString("play " & sMusicFile, 0&, 0, 0) If Play <> 0 Then End If End Sub Public Sub Stop_MP3(Optional ByVal FullFile$) Play = mciSendString("close " & sMusicFile, 0&, 0, 0) End Sub Public Function GetShortPath(ByVal strFileName As String) As String Dim lngRes As Long, strPath As String strPath = String$(165, 0) lngRes = GetShortPathName(strFileName, strPath, 164) GetShortPath = Left$(strPath, lngRes) End Function Function IsFile(ByVal fName As String) As Boolean On Error Resume Next IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory) End Function Public Function AudioFilePath() As String AudioFilePath = CurrentProject.Path & "\Resurce\Audio Files\" End Function Public Function PlayFile(ByVal FileName_ As String) Dim Msg As String Msg = ChrW(1578) & ChrW(1571) & ChrW(1603) & ChrW(1583) & ChrW(32) & ChrW(1605) & ChrW(1606) & ChrW(32) & ChrW(1608) & ChrW(1580) & _ ChrW(1608) & ChrW(1583) & ChrW(32) & ChrW(1605) & ChrW(1587) & ChrW(1575) & ChrW(1585) & ChrW(32) & ChrW(40) & ChrW(32) & _ ChrW(1605) & ChrW(1604) & ChrW(1601) & ChrW(32) & ChrW(47) & ChrW(32) & ChrW(1605) & ChrW(1604) & ChrW(1601) & ChrW(1575) & _ ChrW(1578) & ChrW(41) & ChrW(32) & ChrW(1575) & ChrW(1604) & ChrW(1589) & ChrW(1608) & ChrW(1578) & ChrW(32) & ChrW(46) & _ ChrW(13) & ChrW(10) & ChrW(1578) & ChrW(1571) & ChrW(1603) & ChrW(1583) & ChrW(32) & ChrW(1605) & ChrW(1606) & ChrW(32) & _ ChrW(1608) & ChrW(1580) & ChrW(1608) & ChrW(1583) & ChrW(32) & ChrW(40) & ChrW(32) & ChrW(1605) & ChrW(1604) & ChrW(1601) & _ ChrW(32) & ChrW(47) & ChrW(32) & ChrW(1605) & ChrW(1604) & ChrW(1601) & ChrW(1575) & ChrW(1578) & ChrW(41) & ChrW(32) & _ ChrW(1575) & ChrW(1604) & ChrW(1589) & ChrW(1608) & ChrW(1578) & ChrW(32) & ChrW(1601) & ChrW(1609) & ChrW(32) & ChrW(1575) & _ ChrW(1604) & ChrW(1605) & ChrW(1587) & ChrW(1575) & ChrW(1585) & ChrW(32) & ChrW(1575) & ChrW(1604) & ChrW(1605) & _ ChrW(1581) & ChrW(1583) & ChrW(1583) & ChrW(32) & ChrW(46) & ChrW(13) & ChrW(10) & ChrW(1578) & ChrW(1571) & _ ChrW(1603) & ChrW(1583) & ChrW(32) & ChrW(1605) & ChrW(1606) & ChrW(32) & ChrW(1575) & ChrW(1587) & ChrW(1605) & _ ChrW(32) & ChrW(32) & ChrW(40) & ChrW(32) & ChrW(1605) & ChrW(1604) & ChrW(1601) & ChrW(32) & ChrW(47) & ChrW(32) & _ ChrW(1605) & ChrW(1604) & ChrW(1601) & ChrW(1575) & ChrW(1578) & ChrW(41) & ChrW(32) & ChrW(1575) & ChrW(1604) & _ ChrW(1589) & ChrW(1608) & ChrW(1578) & ChrW(32) & ChrW(46) mp3Path = AudioFilePath & FileName_ & ".mp3" wavPath = AudioFilePath & FileName_ & ".wav" StopFile If IsFile(mp3Path) Then Sound_MP3 (mp3Path): Exit Function If IsFile(wavPath) Then playSound (wavPath), vbNull, SND_ALIAS Or SND_NODEFAULT Or SND_ASYNC: Exit Function If IsFile(mp3Path) = IsFile(wavPath) Then MsgBox (Msg), vbOKOnly + vbMsgBoxRtlReading + vbMsgBoxRight: Exit Function End Function Public Function StopFile() playSound vbNullString, ByVal 0&, SND_NODEFAULT Stop_MP3 (mp3Path) End Function الخطوة الثانية قم بانشاء نموذج باسم ( frmPlayAudio ) الخطوة الثالثة قم بانشاء مربع نص فى النموذج السابق باسم ( txtAudioFileName ) الخطوة الرابعة قم بانشاء زر أمر فى النموذج السابق باسم ( cmdPlay ) وفى حدث عند النقر ضع الكود الاتى soundOn = True: PlayFile (Me.txtAudioFileName) الخطوة الخامسة قم بانشاء زر أمر فى النموذج السابق باسم ( cmdStop ) وفى حدث عند النقر ضع الكود الاتى StopFile الخطوة السادسة فى حدث عند إغلاق النموذج ضع الكود الاتى StopFile الخطوة السابعة بعد حفظ ما سبق افتح النموذج وادخل فى مربع النص ( txtAudioFileName ) اسم ملف الصوت الموجود فى المسار المحدد بدون الامتداد مثلا لو ملف الصوت باسم : MyAudio.mp3 Or MyAudio.wav اسم ملف الصوت فى مربع النص ( txtAudioFileName ) يكون فى الشكل الاتى فقط : MyAudio والان جرب الضغط على زر الامر الخاص بالتشغيل تارة وزر الامر الخاص بالايقاف تارة أخرى طيب ملاحظة مهمه : الطريقة ودوال API هنا تقوم بتشغيل ملفات صوت من النوعين MP3 . WAV <<---< والله دلع شغل فاخر من الأخر تم صياغة الكود بمرونه مطلقة للتعامل مع الملف بغض النظر عن امتداد الملف اه والله زيمبئولك كده مش مصدق ليه مش بئولك شغل فاخر اللى مش عاجبه المسار لملفات الصوت او عاوز يغير مكانها او اسمها طبعا فى الموديول يغير فى الروتين ده على مزاجه AudioFilePath() انا شرحت بالتفصيل الممل اياك حد يقول لى عاوز مرفق أو مش عارف يطبق الشرح